qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
828,139 | I'm trying to get the values from a pointer to a float array, but it returns as c\_void\_p in python
The C code
```
double v;
const void *data;
pa_stream_peek(s, &data, &length);
v = ((const float*) data)[length / sizeof(float) -1];
```
Python so far
```
import ctypes
null_ptr = ctypes.c_void_p()
pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length))
```
The issue being the null\_ptr has an int value (memory address?) but there is no way to read the array?! | 2009/05/06 | [
"https://Stackoverflow.com/questions/828139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/102018/"
] | To use ctypes in a way that mimics your C code, I would suggest (and I'm out-of-practice and this is untested):
```
vdata = ctypes.c_void_p()
length = ctypes.c_ulong(0)
pa_stream_peek(stream, ctypes.byref(vdata), ctypes.byref(length))
fdata = ctypes.cast(vdata, POINTER(float))
``` | You'll also probably want to be passing the null\_ptr using byref, e.g.
```
pa_stream_peek(stream, ctypes.byref(null_ptr), ctypes.c_ulong(length))
``` |
828,139 | I'm trying to get the values from a pointer to a float array, but it returns as c\_void\_p in python
The C code
```
double v;
const void *data;
pa_stream_peek(s, &data, &length);
v = ((const float*) data)[length / sizeof(float) -1];
```
Python so far
```
import ctypes
null_ptr = ctypes.c_void_p()
pa_stream_peek(stream, null_ptr, ctypes.c_ulong(length))
```
The issue being the null\_ptr has an int value (memory address?) but there is no way to read the array?! | 2009/05/06 | [
"https://Stackoverflow.com/questions/828139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/102018/"
] | To use ctypes in a way that mimics your C code, I would suggest (and I'm out-of-practice and this is untested):
```
vdata = ctypes.c_void_p()
length = ctypes.c_ulong(0)
pa_stream_peek(stream, ctypes.byref(vdata), ctypes.byref(length))
fdata = ctypes.cast(vdata, POINTER(float))
``` | When you pass pointer arguments without using ctypes.pointer or ctypes.byref, their contents simply get set to the integer value of the memory address (i.e., the pointer bits). These arguments should be passed with `byref` (or `pointer`, but `byref` has less overhead):
```
data = ctypes.pointer(ctypes.c_float())
nbytes = ctypes.c_sizeof()
pa_stream_peek(s, byref(data), byref(nbytes))
nfloats = nbytes.value / ctypes.sizeof(c_float)
v = data[nfloats - 1]
``` |
4,960,777 | The following Python code tries to create an SQLite database and a table, using the command line in Linux:
```
#!/usr/bin/python2.6
import subprocess
args = ["sqlite3", "db.sqlite", "'CREATE TABLE my_table(my_column TEXT)'"]
print(" ".join(args))
subprocess.call(args)
```
When I ran the code, it created a database with zero bytes and the following output:
```
sqlite3 db.sqlite 'CREATE TABLE my_table(my_column TEXT)'
Error: near "'CREATE TABLE my_table(my_column TEXT)'": syntax error
```
But when I copied the command printed by the code (just above the error message), and pasted the command onto the command line, the command created a database with a table.
What is wrong with the code? | 2011/02/10 | [
"https://Stackoverflow.com/questions/4960777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249487/"
] | Drop the `'` in the second argument to `sqlite` (third element of the `args` list). The `subprocess` module does the quoting on its own and ensures, that the arguments gets passed to the executable as one string. It works on the command line, because there, the `'` are necessary to tell the shell, that it should treat the enclosed string as single entity.
```
args = ["sqlite3", "db.sqlite", "CREATE TABLE my_table(my_column TEXT)"]
```
should work. | Besides the extra quoting that @Dirk mentions before, you can also create the database without spawning a subprocess:
```
import sqlite3
cnx = sqlite3.connect("e:/temp/db.sqlite")
cnx.execute("CREATE TABLE my_table(my_column TEXT)")
cnx.commit()
cnx.close()
``` |
51,576,837 | I have dataset where one of the column holds total sq.ft value.
```
1151
1025
2100 - 2850
1075
1760
```
I would like to split the 2100 - 2850 if the dataframe contains '-' and take its average(mean) as the new value. I am trying achieve this using apply method but running into error when statement containing contains is executing. Please suggest how to handle this situation.
```
def convert_totSqft(s):
if s.str.contains('-', regex=False) == True
<< some statements>>
else:
<< some statements>>
X['new_col'] = X['total_sqft'].apply(convert_totSqft)
```
Error message:
```
File "<ipython-input-6-af39b196879b>", line 2, in convert_totSqft
if s.str.contains('-', regex=False) == True:
AttributeError: 'str' object has no attribute 'str'
``` | 2018/07/29 | [
"https://Stackoverflow.com/questions/51576837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10148648/"
] | IIUC
```
df.col.str.split('-',expand=True).apply(pd.to_numeric).mean(1)
Out[630]:
0 1151.0
1 1025.0
2 2475.0
3 1075.0
4 1760.0
dtype: float64
``` | IIUC, you can `split` by `-` anyway and just `transform` using `np.mean`, once the mean of a single number is just the number itself
```
df.col.str.split('-').transform(lambda s: np.mean([int(x.strip()) for x in s]))
0 1151.0
1 1025.0
2 2475.0
3 1075.0
4 1760.0
```
Alternatively, you can `sum` and divide by `len` (same thing)
```
df.col.str.split('-').transform(lambda s: sum([int(x.strip()) for x in s])/len(s))
```
If want results back necessarily as `int`, just wrap it with `int()`
```
df.col.str.split('-').transform(lambda s: int(np.mean([int(x.strip()) for x in s])))
0 1151
1 1025
2 2475
3 1075
4 1760
``` |
74,057,953 | browser build and python (flask) backend. As far as I understand everything should work, the DOM is identical in both and doesn't change after that, but vue ignores the server-side rendered DOM and generates it from scratch. What surprises me even more is the fact that it does not delete the server's initial rendered DOM, but doubles it in exactly the same way.
How to make vue work with prerendered dom?
console message:
```
vue.esm-browser.js:1617
[Vue warn]: Hydration node mismatch:
- Client vnode: Symbol(Comment)
- Server rendered DOM: " " (text)
at <RouterView>
at <App>
```
```
Hydration complete but contains mismatches.
```
Minimal, Reproducible example:
[on code pen](https://codepen.io/MarcelDev-u/pen/qBYgPZz?editors=1001 "thanks").
My code is quite complex and messy so I isolated the bug to html and js only. | 2022/10/13 | [
"https://Stackoverflow.com/questions/74057953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15810660/"
] | It turned out that the issue for me was formating...
It was working:
```
<div id="app">{{ server rendered html }}</div>
```
It was not:
```
<div id="app">
{{ server rendered html}}
</div>
``` | [This answer](https://stackoverflow.com/a/67978474/8816585) is explaining the use case with a Nuxt configuration but is totally valid for your code too.
The issue here being that you probably have:
* some hardcoded HTML string
* SSR content generated by Vue
* client-side hydrated content by Vue
All of them can have the same content, they will still not behave properly if some of them need to overwrite the previous one.
If you make your markup like this
```html
<div id="app">
<h1></h1>
</div>
```
You will not have any issue because it will only keep Vue SSR + client-side Vue and it will be plugging itself to the `app` id.
If it was in another context, I would recommend disabling JS to try that one out or clicking on "View page source" with your mouse but you will not have a clean result on Codepen.
SSR is a broad topic with a lot of qwirky issues, I recommend that you try that with either Nuxt or at least an SFC Vue setup with Vite to get the full scope and an easier time debugging the whole thing: <https://vuejs.org/guide/quick-start.html#creating-a-vue-application>
Trying out in Codepen is nice but will add more sneaky things I'd say.
So don't spend too much time trying to fix that in this context, try directly into your VScode editor with some Vue devtools for a full explanation of what's happening. |
48,033,519 | ```
import pygame as pg, sys
from pygame.locals import *
import os
pg.mixer.pre_init(44100, 16, 2, 4096)
pg.init()
a = pg.mixer.music.load("./Sounds/ChessDrop2.wav")
a.play()
```
The code above is what I have written to test whether sound can be played through pygame. My 'ChessDrop2.wav' file is a 16 bit wav-PCM file because when the file was 32 bit PCM, pygame recognised it as an unknown format. Now that error is gone when I run the code but the error below pops up on my shell instead. I have assigned the sound file to the variable 'a' so shouldn't the sound play? My version of python is 3.6.1 and pygame is 1.9.3.
```
a.play()
AttributeError: 'NoneType' object has no attribute 'play'
``` | 2017/12/30 | [
"https://Stackoverflow.com/questions/48033519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8965922/"
] | this functions doesn't return any object to be used, check the documentation:
<https://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load>
after loading the file you should use
```
pg.mixer.music.play()
``` | As @CaMMelo stated `pygame.mixer.music.load(filename)` method doesn't return an object.
However, if you are looking for an return object after the load, you may want to try [pygame.mixer.Sound](https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound) .
>
> pygame.mixer.Sound
>
> Create a new Sound object from a file or buffer object
>
>
>
```
from pygame import mixer
mixer.init()
sound = mixer.Sound("yourWaveFile.wav")
sound.play()
``` |
60,754,120 | Does anyone know a solution to this?
EDIT: This question was closed, because the problem didn't seem clear.
So the problem was the error "AttributeError: module 'wx' has no attribute 'adv'", although everything seemed right.
And actually, everything was right, the problem was individual to another PC, where "import wx.adv" resulted in a segmentation fault.
```
$ python
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
>>> wx.version()
'4.0.7.post2 gtk3 (phoenix) wxWidgets 3.0.5'
>>> wx.adv.NotificationMessage
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'wx' has no attribute 'adv'
>>>
```
Or is there any other "non intrusive" notification method? | 2020/03/19 | [
"https://Stackoverflow.com/questions/60754120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647509/"
] | try importing this and run this again
```
import wx.adv
``` | As @arvind8 points out it is a separate import.
At its simplest:
```
import wx
import wx.adv
app = wx.App()
frame = wx.Frame(parent=None, title="Hello, world!")
frame.Show()
m=wx.adv.NotificationMessage("My message","The text I wish to show")
#m.Show(timeout = m.Timeout_Never)
m.Show(timeout = m.Timeout_Auto)
#m.Show(timeout = 5)
app.MainLoop()
```
Note:
the timeout function for the message takes either a number of seconds or one of 2 pre-set values `Never` or `Auto`.
`Auto` is the default. |
54,683,892 | I have a python project with multiple files and a cmd.py which uses argparse to parse the arguments, in the other files there are critical functions. What I want to do is: I want to make it so that if in the command line I were to put `cmd -p hello.txt` it runs that python file.
I was thinking that I could just simply move the cmd.py file to somewhere like `/usr/bin/` or some other directory included in the `$PATH`, however since I have other files which work with my `cmd.py`, there will be multiple files in my `/usr/bin`.
Another thing that I could do is to make a symbolic link between the `cmd.py` and `/usr/bin/cmd` like this: `ln -s /path/to/cmd.py /usr/bin/cmd`, but then where do i put the cmd.py? and is this best practice?
Note: I intend for this to work on Linux and MacOS X, not windows | 2019/02/14 | [
"https://Stackoverflow.com/questions/54683892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8585864/"
] | The usual way to do this is to define a set of entry points in `setup.py` and let the packaging infrastructure do the heavy lifting for you.
```
setup(
# ...
entry_points = {
'console_scripts': ['cmd = cmd:main'],
}
)
```
This requires `setuptools`.
Here is some documentation for this facility: <https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html> | For one thing I don't recommend installation in `/usr/bin` as that's where system programs go. `/usr/local/bin` or another custom directory added to `$PATH` could be appropriate.
As for getting it to run like a typical program, name it `cmd`, wherever you put it, as the extension is not necessary, and add this line to the top of the program:
```sh
#!/usr/bin/env python
```
(You may want to specify `python3` instead of just `python` if you want to ensure Python 3.x is used.)
Then it can be made executable with `chmod +x <path to your program>`. Ensure that you have the necessary privileges to do this (i.e. `sudo` may be necessary). |
54,683,892 | I have a python project with multiple files and a cmd.py which uses argparse to parse the arguments, in the other files there are critical functions. What I want to do is: I want to make it so that if in the command line I were to put `cmd -p hello.txt` it runs that python file.
I was thinking that I could just simply move the cmd.py file to somewhere like `/usr/bin/` or some other directory included in the `$PATH`, however since I have other files which work with my `cmd.py`, there will be multiple files in my `/usr/bin`.
Another thing that I could do is to make a symbolic link between the `cmd.py` and `/usr/bin/cmd` like this: `ln -s /path/to/cmd.py /usr/bin/cmd`, but then where do i put the cmd.py? and is this best practice?
Note: I intend for this to work on Linux and MacOS X, not windows | 2019/02/14 | [
"https://Stackoverflow.com/questions/54683892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8585864/"
] | The usual way to do this is to define a set of entry points in `setup.py` and let the packaging infrastructure do the heavy lifting for you.
```
setup(
# ...
entry_points = {
'console_scripts': ['cmd = cmd:main'],
}
)
```
This requires `setuptools`.
Here is some documentation for this facility: <https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html> | 1. You can add a folder to your path.
* in .bashrc add following
* export PATH=[New\_Folder\_Path]:$PATH
2. put the python program in your path\_folder created at step 1.
3. make it executable : chmod u+x [filename]
4. open a new terminal, and you should be able to call the python program
5. NOTE: make sure to put the shebang in your python-file : #!/usr/bin/env python3 |
23,021,864 | I've added Python's logging module to my code to get away from a galloping mess of print statements and I'm stymied by configuration errors. The error messages aren't very informative.
```
Traceback (most recent call last):
File "HDAudioSync.py", line 19, in <module>
logging.config.fileConfig('../conf/logging.conf')
File "/usr/lib64/python2.6/logging/config.py", line 84, in fileConfig
handlers = _install_handlers(cp, formatters)
File "/usr/lib64/python2.6/logging/config.py", line 162, in _install_handlers
h = klass(*args)
TypeError: __init__() takes at most 5 arguments (21 given)
```
Nothing in my config file gives 21 arguments.
Here is the config file
```
[loggers]
keys=root,main, sftp, jobapi
[handlers]
keys=console, logfile, syslog
[formatters]
keys=simple, timestamp
[logger_root]
level=NOTSET
handlers=logfile
[logger_main]
level=DEBUG
handlers=console, logfile, syslog
propagate=1
qualname=main
[logger_sftp]
level=DEBUG
handlers=console, logfile, syslog
propagate=1
qualname=sftp
[logger_jobapi]
level=DEBUG
handlers=console, logfile, syslog
propagate=1
qualname=jobapi
[handler_console]
class=StreamHandler
level=DEBUG
formatter=simple
args=(sys.stdout,)
[handler_logfile]
class=FileHandler
level=DEBUG
formatter=timestamp
args=('../log/audiosync.log')
[handler_syslog]
class=FileHandler
level=WARN
formatter=timestamp
args=('../log/audiosync.sys.log')
[formatter_simple]
format=%(levelname)s - %(message)s
[formatter_timestamp]
format=%(asctime)s - %(name)s -%(levelname)s - %(message)s
```
and here is the logging init code in my main module:
```
import logging
import logging.config
import logging.handlers
logging.config.fileConfig('../conf/logging.conf')
logger = logging.getLogger('main')
```
I'm not so much looking for what I did wrong here (though that would be nice) as for a methodology for debugging this.
Thanks. | 2014/04/11 | [
"https://Stackoverflow.com/questions/23021864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/811299/"
] | You can dig into the Python source code to investigate these sorts of problems. Much of the library is implemented in Python and is pretty readable without needing to know the inner details of the interpreter. [hg.python.org](http://hg.python.org/cpython/file/a8f3ca72f703/Lib/logging/config.py) provides a web interface to the repository that is convenient for browsing. I couldn't find the branch for 2.6 but the relevant statement is on line 147 in the current revision.
You can see that `args` is generated from an eval which is getting the value of the `args` key from each `handler_*` section of the config file. That args variable is then expanded with an unpack (\*) operation to create arguments for klass().
In your config file you have this line:
```
args=('../log/audiosync.log')
```
It is a 20-character string that is being unpacked into a tuple of individual characters which, along with the `self` object passed to `__init__`, accounts for the 21 arguments in the error message. You are missing a trailing comma needed to make a 1-element tuple:
```
args=('../log/audiosync.log',)
^-- missing
```
The same bug is in the `handler_syslog` section. | ### Look for keywords
The last two lines of the traceback contain the word `handler` (`handler = ...` and `_install_handlers`). That gives you a starting point to look at the handler definitions in your config file.
### Look for matching values *everywhere*
If a function takes 5 arguments, but you've somehow given over 4x that amount, something was not parsed the way you expected it to be. Especially when a quick glance at your config file doesn't show anything near that number.
I've found one of the biggest causes of this kind of discrepancy is passing a string when a function is expecting a list, tuple, or object. The underlying code may split that string into characters and use that for arguments.
In your case, the first option I can find is in this block in your config:
```
[handler_syslog]
class=FileHandler
level=WARN
formatter=timestamp
args=('../log/audiosync.sys.log')
```
There are no 21 character strings by themselves, but if you strip out the leading `../` from the args, you are left with `log/audiosync.sys.log` which is a 21 character string.
### Use a debugger
That's what they're there for. Use [pdb](https://docs.python.org/2/library/pdb.html), or a visual debugger like [PyCharm](http://www.jetbrains.com/pycharm/%E2%80%8E) or [PyDev](http://pydev.org/). Then, you can step through the code line by line, and check variable values throughout.
### Change the logging level
Some modules allow you to set their logging level. You can set it to `DEBUG` to see everything the developers have ever set to log. It can help you to follow the flow of the application as it runs. I don't think this is available for the ConfigParser module, but it is available at times.
### If all else fails, read the source
[The Python source code is available online](http://hg.python.org/). If you're getting semi-cryptic tracebacks and find it difficult to obtain context, you can always download the source, and run through the code manually. |
65,367,490 | I have a python data frame like this
```
ID ID_1 ID_2 ID_3 ID_4 ID_5
ID_1 1.0 20.1 31.0 23.1 31.5
ID_2 3.0 1.0 23.0 90.0 21.5
ID_3. 7.0 70.1 1.0 23.0 31.5
ID_4. 9.0 90.1 43.0 1.0 61.5
ID_5 11.0 10.1 11.0 23.0 1.0
```
I need to update values where COLUMN NAMES are equal to the ID values and then set the values to zero.
for example in the first row the ID value (ID\_1) matches with first column ID\_1 and I need to reset the value of 1.0 to zero , and similarly for second row , the ID value (ID\_2) matches with second column ID\_2 and reset the value of 1.0 to zero.
How do I do this in Python ? I am very new in python. Can anyone please help.
the expected output would be like this -
```
ID ID_1 ID_2 ID_3 ID_4 ID_5
ID_1 0.0 20.1 31.0 23.1 31.5
ID_2 3.0 0.0 23.0 90.0 21.5
ID_3. 7.0 70.1 0.0 23.0 31.5
ID_4. 9.0 90.1 43.0 0.0 61.5
ID_5 11.0 10.1 11.0 23.0 0.0
``` | 2020/12/19 | [
"https://Stackoverflow.com/questions/65367490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4726029/"
] | Consider `df`:
```
In [1479]: df
Out[1479]:
ID ID_1 ID_2 ID_3 ID_4 ID_5 ID_6
0 ID_1 1.0 20.1 31.0 23.0 31.5 24.6
1 ID_2 3.0 1.0 23.0 90.0 21.5 24.6
2 ID_3 7.0 70.1 1.0 23.0 31.5 24.6
3 ID_4 9.0 90.1 43.0 1.0 61.5 24.6
4 ID_5 11.0 10.1 11.0 23.0 1.0 24.6
5 ID_6 7.0 20.1 31.0 33.0 87.5 1.0
```
Use [`pd.get_dummies`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html) with [`df.combine_first`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine_first.html):
```
In [1477]: import numpy as np
In [1497]: df.iloc[:, 1:] = pd.get_dummies(df['ID']).replace({0: np.nan, 1: 0}).combine_first(df.iloc[:, 1:])
In [1498]: df
Out[1498]:
ID ID_1 ID_2 ID_3 ID_4 ID_5 ID_6
0 ID_1 0.0 20.1 31.0 23.0 31.5 24.6
1 ID_2 3.0 0.0 23.0 90.0 21.5 24.6
2 ID_3 7.0 70.1 0.0 23.0 31.5 24.6
3 ID_4 9.0 90.1 43.0 0.0 61.5 24.6
4 ID_5 11.0 10.1 11.0 23.0 0.0 24.6
5 ID_6 7.0 20.1 31.0 33.0 87.5 0.0
``` | Let's try broadcasting:
```
df[:] = np.where(df['ID'].values[:,None] == df.columns.values,0, df)
```
Output:
```
ID ID_1 ID_2 ID_3 ID_4 ID_5
0 ID_1 0.0 20.1 31.0 23.1 31.5
1 ID_2 3.0 0.0 23.0 90.0 21.5
2 ID_3 7.0 70.1 0.0 23.0 31.5
3 ID_4 9.0 90.1 43.0 0.0 61.5
4 ID_5 11.0 10.1 11.0 23.0 0.0
``` |
30,982,532 | I'm trying to connect to JIRA using a Python wrapper for the Rest interface and I can't get it to work at all. I've read everything I could find so this is my last resort.
I've tried a lot of stuff including
>
> verify=False
>
>
>
but nothing has worked so far.
The strange thing is that with urllib.request it does work without any SSL cert (it's just some internal cert) but the goal is to use the Python Jira wrapper so it's not really an option...
I've tried Python 3.4 and 2.7... getting desperate...
Any ideas?
The code is very simple:
```
import requests
r = requests.get('https://jiratest.myurl.com/rest/api/2/serverInfo')
print(r.content)
```
Error:
```
C:\Python34\python.exe C:/projects/jirascriptsx/delete_worklogs.py
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 544, in urlopen
body=body, headers=headers)
File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 341, in _make_request
self._validate_conn(conn)
File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 761, in _validate_conn
conn.connect()
File "C:\Python34\lib\site-packages\requests\packages\urllib3\connection.py", line 238, in connect
ssl_version=resolved_ssl_version)
File "C:\Python34\lib\site-packages\requests\packages\urllib3\util\ssl_.py", line 279, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "C:\Python34\lib\ssl.py", line 365, in wrap_socket
_context=self)
File "C:\Python34\lib\ssl.py", line 583, in __init__
self.do_handshake()
File "C:\Python34\lib\ssl.py", line 810, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\requests\adapters.py", line 370, in send
timeout=timeout
File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 574, in urlopen
raise SSLError(e)
requests.packages.urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/projects/jirascriptsx/delete_worklogs.py", line 4, in <module>
r = requests.get('https://jiratest.uniqa.at/rest/api/2/serverInfo')
File "C:\Python34\lib\site-packages\requests\api.py", line 69, in get
return request('get', url, params=params, **kwargs)
File "C:\Python34\lib\site-packages\requests\api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 465, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python34\lib\site-packages\requests\sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "C:\Python34\lib\site-packages\requests\adapters.py", line 431, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)
Process finished with exit code 1
``` | 2015/06/22 | [
"https://Stackoverflow.com/questions/30982532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2314427/"
] | The actual enum behavior of instatiating the instance [doesn't have an issue with thread safety](https://stackoverflow.com/a/2531881/1424875). However, you will need to make sure that the instance state itself is thread-safe.
The interactions with the fields and methods of `Application` are the risk--using either careful synchronization and locking, or purely concurrent data and careful verification that other inconsistencies can't happen, will be your best bet here. | Singleton ensures you only have one instance of a class per class loader.
You only have to take care about concurrency if your singleton has a mutable state. I mean if singleton persist some kind of mutable data.
In this case you should use some kind of synchronization-locking mechanishm to prevent concurrent modification of the state and/or use thread-safe data structures. |
45,425,026 | ---
*tldr:* How is Python set up on a Mac? Is there a ton of senseless copying going on even before I start wrecking it?
--------------------------------------------------------------------------------------------------------------------
I am hoping to get some guidance regarding Python system architecture on Mac (perhaps the answer is OS agnostic, but I assume for safety's sake that it is not).
I can run a variety of commands that *seem* to give me multiple Python binaries. In truth, there may be more this is just what I have come across so far.
1. `ls /usr/local/bin/ | grep 'python\|pyd'`
`pydoc
pydoc2
pydoc2.7
python
python-32
python-config
python2
python2-32
python2-config
python2.7
python2.7-32
python2.7-config
pythonw
pythonw-32
pythonw2
pythonw2-32
pythonw2.7
pythonw2.7-32`
2. `ls /usr/bin | grep 'python\|pyd'`
`pydoc
pydoc2.6
pydoc2.7
python
python-config
python2.6
python2.6-config
python2.7
python2.7-config
pythonw
pythonw2.6
pythonw2.7`
3. `ls /Library/Frameworks/Python.framework/Versions/`
`2.7 Current`
4. `ls /System/Library/Frameworks/Python.framework/Versions/`
`2.3 2.5 2.6 2.7 Current`
As far as which one runs when executing a `.py`; when I run `which python` I get back
`/Library/Frameworks/Python.framework/Versions/2.7/bin/python`
This seems consistent when I use the REPL. The `site-packages` relative to this install are available (not that I tinkered with other site package locs)
I have not made any serious modifications to my python environment on my Mac so I am assuming this is what is given to users out of the box. If anyone understands how all these binaries fit together and why they all exist please let me know. If the answer is RTM please simply point me to a page as <https://docs.python.org/2/using/mac.html> did not suffice.
Thanks for making me smarter!
SPECS:
Mac OS: 10.12.5 | 2017/07/31 | [
"https://Stackoverflow.com/questions/45425026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619510/"
] | Sadly that's not how Bootstrap works; you get a single row that you can place columns within and you can't float another column underneath others and have it all automatically adjust like your diagram.
I would suggest checking out the jQuery plugin called [Masonry](https://masonry.desandro.com/) which does help with layouts like you are looking for. | [Bootstrap4](https://v4-alpha.getbootstrap.com/) might help with [flexbox](https://v4-alpha.getbootstrap.com/utilities/flexbox/) inbricated.
Not too sure this is the best example, it still does require some extra CSS to have it run properly:
```css
.container>.d-flex>.col {
box-shadow: 0 0 0 3px turquoise;
min-height: 1.5rem;
height: auto!important;
margin: 0 0 20px;
}
.w-100,
.flex-row.d-flex.col>.border {
box-shadow: 0 0 0 3px turquoise;
}
.w-100 {
margin: -10px 10px 20px
}
.container>.col {
margin: 10px 0;
}
.d-flex.flex-column.col>div {
flex: 1 0 auto;
}
.d-flex.flex-column.col>div.big {/* big or whatever classname you think meaningfull */
flex: 1 1 100%;
}
.col .col:hover {
font-size: 0.5em;
}
```
```html
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="container d-flex flex-wrap flex-row">
<div class="d-flex flex-column col ">
<div class="d-flex col rounded">
AAAA
</div>
<div class="flex-row d-flex col rounded">
<div class="col">1</div>
<div class="col border">2</div>
<div class="col">3</div>
</div>
<div class="d-flex col rounded">
CCCC
</div>
<div class="d-flex col rounded">
DDDD
</div>
</div>
<div class="d-flex flex-column col">
<div class="d-flex flex-column col rounded">
<h1>hover me </h1><br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE
</div>
</div>
<div class="d-flex flex-column col">
<div class="d-flex col rounded">
<p>FF<br/>FF</p>
</div>
<div class="flex-row d-flex col rounded">
<div class="col">1</div>
<div class="col border">2</div>
<div class="col">3</div>
</div>
<div class="d-flex col big rounded">
HHHH
</div>
</div>
<div class="w-100 rounded"> IIII</div>
```
<https://codepen.io/gc-nomade/pen/LjNroE>
---
**Another** example from a **boostrap3** structure and **`flex` rules added in the CSS**
```css
.flex, .flexcol {
display:flex;/* rule around which the flex layout is build, remove it to fall back to regular bootstrap */
}
.row {
padding:0 20px ;
margin:auto;
text-align:center;
}
.flexcol {
padding:0;
}
.colchild , .footer{
border:solid gray;
color:white;
margin:10px;
background:linear-gradient(20deg, rgba(0,0,0,0.4), rgba(255,255,255,0.4)) tomato;
box-shadow:inset 0 0 3px, 0 0 0 3px orange , 0 0 0 6px turquoise;
}
.flexcol {
flex-direction:column;
}
.col {
flex:1;
padding:1em;
}
.colchild.flex .col:nth-child(2) {
border-left:solid gray;
border-right:solid gray;
}
.rounded {
border-radius:0.5em;
}
```
```html
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row container flex">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 flexcol ">
<div class="colchild rounded">
<p>boxe</p>
</div>
<div class="colchild rounded flex">
<div class="col"> 1 </div>
<div class="col"> 2 </div>
<div class="col"> 3 </div>
</div>
<div class="colchild rounded">
<p>boxe</p>
</div>
<div class="colchild rounded">
<p>boxe</p>
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 flexcol ">
<div class="colchild rounded col">
<p>boxe</p>
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 flexcol ">
<div class="colchild rounded">
<p>boxe</p>
</div>
<div class="colchild rounded flex">
<div class="col"> 1 </div>
<div class="col"> 2 </div>
<div class="col"> 3 </div>
</div>
<div class="colchild rounded col ">
<p>bottom</p>
</div>
</div>
</div>
<div class="row container flex">
<div class="footer w-100 col rounded">footer</div>
```
<https://codepen.io/gc-nomade/pen/VzKvKv/> |
45,425,026 | ---
*tldr:* How is Python set up on a Mac? Is there a ton of senseless copying going on even before I start wrecking it?
--------------------------------------------------------------------------------------------------------------------
I am hoping to get some guidance regarding Python system architecture on Mac (perhaps the answer is OS agnostic, but I assume for safety's sake that it is not).
I can run a variety of commands that *seem* to give me multiple Python binaries. In truth, there may be more this is just what I have come across so far.
1. `ls /usr/local/bin/ | grep 'python\|pyd'`
`pydoc
pydoc2
pydoc2.7
python
python-32
python-config
python2
python2-32
python2-config
python2.7
python2.7-32
python2.7-config
pythonw
pythonw-32
pythonw2
pythonw2-32
pythonw2.7
pythonw2.7-32`
2. `ls /usr/bin | grep 'python\|pyd'`
`pydoc
pydoc2.6
pydoc2.7
python
python-config
python2.6
python2.6-config
python2.7
python2.7-config
pythonw
pythonw2.6
pythonw2.7`
3. `ls /Library/Frameworks/Python.framework/Versions/`
`2.7 Current`
4. `ls /System/Library/Frameworks/Python.framework/Versions/`
`2.3 2.5 2.6 2.7 Current`
As far as which one runs when executing a `.py`; when I run `which python` I get back
`/Library/Frameworks/Python.framework/Versions/2.7/bin/python`
This seems consistent when I use the REPL. The `site-packages` relative to this install are available (not that I tinkered with other site package locs)
I have not made any serious modifications to my python environment on my Mac so I am assuming this is what is given to users out of the box. If anyone understands how all these binaries fit together and why they all exist please let me know. If the answer is RTM please simply point me to a page as <https://docs.python.org/2/using/mac.html> did not suffice.
Thanks for making me smarter!
SPECS:
Mac OS: 10.12.5 | 2017/07/31 | [
"https://Stackoverflow.com/questions/45425026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619510/"
] | I don't see any reason why this couldn't work. The trick is that it has to be done in two rows.
The first row should contain 3 columns. In each of those 3 columns, you can create any number of rows that you need.
The second row contains only 1 full-width column.
Please see the code sample below for a better explanation:
```
<div class="container">
<div class="row" style="height:200px;">
<div class="col-md-4" style="height: 100%;">
<div class="row" style="height:100%;">
<div class="col-md-12" style="height:25%">12 Columns</div>
<div class="col-md-4" style="height:25%">4 Columns</div>
<div class="col-md-4" style="height:25%">4 Columns</div>
<div class="col-md-4" style="height:25%">4 Columns</div>
<div class="col-md-12" style="height:50%">12 Columns</div>
</div>
</div>
<div class="col-md-4" style="height: 100%;">
<div class="row" style="height:100%;">
<div class="col-md-12" style="height:100%">12 Columns</div>
</div>
<div class="row">
</div>
</div>
<div class="col-md-4" style="height: 100%;">
<div class="row" style="height:100%;">
<div class="col-md-12" style="height:25%">12 Columns</div>
<div class="col-md-12" style="height:25%">12 Columns</div>
<div class="col-md-12" style="height:25%">12 Columns</div>
<div class="col-md-12" style="height:25%">12 Columns</div>
</div>
</div>
</div>
<div class="row" style="height:50px;">
<div class="col-md-12" style="height:100%">12 Columns</div>
</div>
</div>
``` | [Bootstrap4](https://v4-alpha.getbootstrap.com/) might help with [flexbox](https://v4-alpha.getbootstrap.com/utilities/flexbox/) inbricated.
Not too sure this is the best example, it still does require some extra CSS to have it run properly:
```css
.container>.d-flex>.col {
box-shadow: 0 0 0 3px turquoise;
min-height: 1.5rem;
height: auto!important;
margin: 0 0 20px;
}
.w-100,
.flex-row.d-flex.col>.border {
box-shadow: 0 0 0 3px turquoise;
}
.w-100 {
margin: -10px 10px 20px
}
.container>.col {
margin: 10px 0;
}
.d-flex.flex-column.col>div {
flex: 1 0 auto;
}
.d-flex.flex-column.col>div.big {/* big or whatever classname you think meaningfull */
flex: 1 1 100%;
}
.col .col:hover {
font-size: 0.5em;
}
```
```html
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="container d-flex flex-wrap flex-row">
<div class="d-flex flex-column col ">
<div class="d-flex col rounded">
AAAA
</div>
<div class="flex-row d-flex col rounded">
<div class="col">1</div>
<div class="col border">2</div>
<div class="col">3</div>
</div>
<div class="d-flex col rounded">
CCCC
</div>
<div class="d-flex col rounded">
DDDD
</div>
</div>
<div class="d-flex flex-column col">
<div class="d-flex flex-column col rounded">
<h1>hover me </h1><br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE<br/>EEEE
</div>
</div>
<div class="d-flex flex-column col">
<div class="d-flex col rounded">
<p>FF<br/>FF</p>
</div>
<div class="flex-row d-flex col rounded">
<div class="col">1</div>
<div class="col border">2</div>
<div class="col">3</div>
</div>
<div class="d-flex col big rounded">
HHHH
</div>
</div>
<div class="w-100 rounded"> IIII</div>
```
<https://codepen.io/gc-nomade/pen/LjNroE>
---
**Another** example from a **boostrap3** structure and **`flex` rules added in the CSS**
```css
.flex, .flexcol {
display:flex;/* rule around which the flex layout is build, remove it to fall back to regular bootstrap */
}
.row {
padding:0 20px ;
margin:auto;
text-align:center;
}
.flexcol {
padding:0;
}
.colchild , .footer{
border:solid gray;
color:white;
margin:10px;
background:linear-gradient(20deg, rgba(0,0,0,0.4), rgba(255,255,255,0.4)) tomato;
box-shadow:inset 0 0 3px, 0 0 0 3px orange , 0 0 0 6px turquoise;
}
.flexcol {
flex-direction:column;
}
.col {
flex:1;
padding:1em;
}
.colchild.flex .col:nth-child(2) {
border-left:solid gray;
border-right:solid gray;
}
.rounded {
border-radius:0.5em;
}
```
```html
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row container flex">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 flexcol ">
<div class="colchild rounded">
<p>boxe</p>
</div>
<div class="colchild rounded flex">
<div class="col"> 1 </div>
<div class="col"> 2 </div>
<div class="col"> 3 </div>
</div>
<div class="colchild rounded">
<p>boxe</p>
</div>
<div class="colchild rounded">
<p>boxe</p>
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 flexcol ">
<div class="colchild rounded col">
<p>boxe</p>
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 flexcol ">
<div class="colchild rounded">
<p>boxe</p>
</div>
<div class="colchild rounded flex">
<div class="col"> 1 </div>
<div class="col"> 2 </div>
<div class="col"> 3 </div>
</div>
<div class="colchild rounded col ">
<p>bottom</p>
</div>
</div>
</div>
<div class="row container flex">
<div class="footer w-100 col rounded">footer</div>
```
<https://codepen.io/gc-nomade/pen/VzKvKv/> |
23,449,320 | How to write something like `!(str.endswith())` in python
I mean I want to check if string IS NOT ending with something.
My code is
```
if text == text. upper(): and text.endswith("."):
```
But I want to put IS NOT after and
writing
```
if text == text. upper(): and not text.endswith("."):
```
or
```
if text == text. upper(): and not(text.endswith(".")):
```
gives me **Invalid syntax** | 2014/05/03 | [
"https://Stackoverflow.com/questions/23449320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678855/"
] | You can use `not`
```
if not str.endswith():
```
your code can be modified to:
```
if text == text.upper() and not text.endswith("."):
``` | You can just use the `not()` oporator:
```
not(str.endswith())
```
EDIT:
Like so:
```
if text == text. upper() and not(text.endswith(".")):
do stuff
```
or
```
if text == text. upper() and not(text.endswith(".")):
do studff
``` |
23,449,320 | How to write something like `!(str.endswith())` in python
I mean I want to check if string IS NOT ending with something.
My code is
```
if text == text. upper(): and text.endswith("."):
```
But I want to put IS NOT after and
writing
```
if text == text. upper(): and not text.endswith("."):
```
or
```
if text == text. upper(): and not(text.endswith(".")):
```
gives me **Invalid syntax** | 2014/05/03 | [
"https://Stackoverflow.com/questions/23449320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678855/"
] | You have an extra colon:
```
if text == text. upper(): and not text.endswith("."):
# ^
```
Remove it and your code should work fine:
```
if text == text.upper() and not text.endswith("."):
``` | You can use `not`
```
if not str.endswith():
```
your code can be modified to:
```
if text == text.upper() and not text.endswith("."):
``` |
23,449,320 | How to write something like `!(str.endswith())` in python
I mean I want to check if string IS NOT ending with something.
My code is
```
if text == text. upper(): and text.endswith("."):
```
But I want to put IS NOT after and
writing
```
if text == text. upper(): and not text.endswith("."):
```
or
```
if text == text. upper(): and not(text.endswith(".")):
```
gives me **Invalid syntax** | 2014/05/03 | [
"https://Stackoverflow.com/questions/23449320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678855/"
] | You have an extra colon:
```
if text == text. upper(): and not text.endswith("."):
# ^
```
Remove it and your code should work fine:
```
if text == text.upper() and not text.endswith("."):
``` | You can just use the `not()` oporator:
```
not(str.endswith())
```
EDIT:
Like so:
```
if text == text. upper() and not(text.endswith(".")):
do stuff
```
or
```
if text == text. upper() and not(text.endswith(".")):
do studff
``` |
43,148,235 | I want python with selenium webdriver to do the following:-
1. Open Facebook
2. Login
3. Click and open the user pane which has the "Logout" option
A small arrow opens the user pane
I wrote the following script
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver=webdriver.Firefox()
def open_url(url):
driver.get(url)
assert "Facebook" in driver.title
def login(user_id,user_pass):
elem_id=driver.find_element_by_name("email")
elem_id.clear()
elem_id.send_keys(user_id)
elem_pass=driver.find_element_by_name("pass")
elem_pass.clear()
elem_pass.send_keys(user_pass)
elem_pass.send_keys(Keys.RETURN)
def search():
wait=WebDriverWait(driver,30)
pane=driver.find_element_by_id("userNavigationLabel").click()
open_url("https://www.fb.com")
login("myuserid","mypass")
search()
```
The following error is what i get
```
selenium.common.exceptions.NoSuchElementException: Message: Unable to
locate element: [id="userNavigationLabel"]
```
How should i locate the element? | 2017/03/31 | [
"https://Stackoverflow.com/questions/43148235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7236897/"
] | How about using macros only instead of using variables and enumerations.
```
//libnameConf.h
#define LIBNAME_A
// #define LIBNAME_B // Uncomment this line and both comment the above line while changing libs.
```
Then we use several conditional compilation statements like this.
```
//libname.c
double coef_arr_a[100] = {...};
double coef_arr_b[100] = {...};
#ifdef LIBNAME_A
somestruct.waveCoefs = coef_arr_a;
//do other coef_arr_a specific stuff
#endif
#ifdef LIBNAME_B
somestruct.waveCoefs = coef_arr_b;
#endif
``` | Sounds like you need [conditional compilaiton](https://en.wikipedia.org/wiki/Conditional_compilation) in C but the way you're doing it is not correct. Conditional compilation is a concept of the [preprocessor](https://en.wikipedia.org/wiki/Preprocessor) which is run before the compiler. The point of preprocessor is to manipulate the source code before it is fed to the compiler. Since you haven't used any preprocessor conditionals, all the source code is fed to the compiler regardless of your compile-time conditionals. You should definitely use preprocessor conditionals to reduce your binary. |
3,093,352 | Is there a method to pass a [variable number of arguments](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists) to a function and have it change those arguments using the `( *args, **keywords )` style of argument passing? I've tried a few things but either see no change or have an error raised by the compiler:
```
def foo( *args ):
args[0] = 4
```
This gets me `TypeError: object does not support assignment` (they're tuples.) Or
```
def foo( *args ):
plusOne = [ item+1 for item in args ]
args = plusOne
```
which has no effect what so ever. If there is no mechanism nor work around I can admit defeat.
Edit:
To clarify why I'm trying to go this route, consider the case here:
```
class bar(object):
def __init__(self,obj):
self.obj = obj
def foo( input ):
input.obj = "something else"
```
If I pass my `bar` object into foo, I get a change in the state. To create a decorator which performs a `deepcopy` which resets all such state I'm currently customizing it for N arguments. I'd like to create one which accepts any number of arguments. Hence, the question. | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178060/"
] | No - Python uses [call by object-sharing](http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing), also known as call-by-value.
To clarify the terminology: you are not receiving a deep copy of the object, but a copy of the object **reference**. Note: this is not the same as [call-by-reference](http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference)! You can think of it as call by value, and that the values are references to objects.
So to answer your question, you receive a copy of the arguments (object references). You cannot modify the object references as if they were passed by reference. You can make a new modified copy of them if you want, but judging from your examples that isn't what you are looking for. The calling scope won't see your changes.
If instead you *mutate* the objects you receive, the client *can* see those changes. | The reason
```
args[0] = 4
```
doesn't work is because, as the error message says, `args` a tuple, which is immutable. So, you'll need it convert it to the mutable object first, for example like this:
```
>>> def foo( *args ):
print(args)
args = list(args)
args[0] = 42
print(args)
>>> foo(23)
(23,)
[42]
```
If you give more information, it would be possible to provide more pythonic solution, because what you're doing seems strange. Also, second code seem to work just fine.
For example the following works just fine and changes calling scope variable:
```
>>> def spam(*a):
a[0][0] = 42
>>> l = [23, 32]
>>> spam(l)
>>> l
[42, 32]
```
The reason being exactly the same: mutability of the `l` object. The same can be shown on your example:
```
>>> def foo( *input ):
input[0].obj = "something else"
>>> b = bar('abc')
>>> foo(b)
>>> b.obj
'something else'
``` |
3,093,352 | Is there a method to pass a [variable number of arguments](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists) to a function and have it change those arguments using the `( *args, **keywords )` style of argument passing? I've tried a few things but either see no change or have an error raised by the compiler:
```
def foo( *args ):
args[0] = 4
```
This gets me `TypeError: object does not support assignment` (they're tuples.) Or
```
def foo( *args ):
plusOne = [ item+1 for item in args ]
args = plusOne
```
which has no effect what so ever. If there is no mechanism nor work around I can admit defeat.
Edit:
To clarify why I'm trying to go this route, consider the case here:
```
class bar(object):
def __init__(self,obj):
self.obj = obj
def foo( input ):
input.obj = "something else"
```
If I pass my `bar` object into foo, I get a change in the state. To create a decorator which performs a `deepcopy` which resets all such state I'm currently customizing it for N arguments. I'd like to create one which accepts any number of arguments. Hence, the question. | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178060/"
] | The reason
```
args[0] = 4
```
doesn't work is because, as the error message says, `args` a tuple, which is immutable. So, you'll need it convert it to the mutable object first, for example like this:
```
>>> def foo( *args ):
print(args)
args = list(args)
args[0] = 42
print(args)
>>> foo(23)
(23,)
[42]
```
If you give more information, it would be possible to provide more pythonic solution, because what you're doing seems strange. Also, second code seem to work just fine.
For example the following works just fine and changes calling scope variable:
```
>>> def spam(*a):
a[0][0] = 42
>>> l = [23, 32]
>>> spam(l)
>>> l
[42, 32]
```
The reason being exactly the same: mutability of the `l` object. The same can be shown on your example:
```
>>> def foo( *input ):
input[0].obj = "something else"
>>> b = bar('abc')
>>> foo(b)
>>> b.obj
'something else'
``` | If you want to change the arguments passed to the functions, so that you could do something like this:
```
>>> x, y = (10, 17)
>>> foo(x, y)
>>> print (x, y)
(11, 18)
```
you're out of luck, for the reason stated in Mark's answer.
However, if you're passing mutable objects to your function you can change these objects and see the results after calling `foo`:
```
def foo(*args):
for arg in args:
arg['value'] += 1
>>> d1 = {'value': 1}
>>> d2 = {'value': 2}
>>> foo(d1, d2)
>>> print (d1, d2)
({'value': 2}, {'value': 3})
``` |
3,093,352 | Is there a method to pass a [variable number of arguments](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists) to a function and have it change those arguments using the `( *args, **keywords )` style of argument passing? I've tried a few things but either see no change or have an error raised by the compiler:
```
def foo( *args ):
args[0] = 4
```
This gets me `TypeError: object does not support assignment` (they're tuples.) Or
```
def foo( *args ):
plusOne = [ item+1 for item in args ]
args = plusOne
```
which has no effect what so ever. If there is no mechanism nor work around I can admit defeat.
Edit:
To clarify why I'm trying to go this route, consider the case here:
```
class bar(object):
def __init__(self,obj):
self.obj = obj
def foo( input ):
input.obj = "something else"
```
If I pass my `bar` object into foo, I get a change in the state. To create a decorator which performs a `deepcopy` which resets all such state I'm currently customizing it for N arguments. I'd like to create one which accepts any number of arguments. Hence, the question. | 2010/06/22 | [
"https://Stackoverflow.com/questions/3093352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178060/"
] | No - Python uses [call by object-sharing](http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing), also known as call-by-value.
To clarify the terminology: you are not receiving a deep copy of the object, but a copy of the object **reference**. Note: this is not the same as [call-by-reference](http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference)! You can think of it as call by value, and that the values are references to objects.
So to answer your question, you receive a copy of the arguments (object references). You cannot modify the object references as if they were passed by reference. You can make a new modified copy of them if you want, but judging from your examples that isn't what you are looking for. The calling scope won't see your changes.
If instead you *mutate* the objects you receive, the client *can* see those changes. | If you want to change the arguments passed to the functions, so that you could do something like this:
```
>>> x, y = (10, 17)
>>> foo(x, y)
>>> print (x, y)
(11, 18)
```
you're out of luck, for the reason stated in Mark's answer.
However, if you're passing mutable objects to your function you can change these objects and see the results after calling `foo`:
```
def foo(*args):
for arg in args:
arg['value'] += 1
>>> d1 = {'value': 1}
>>> d2 = {'value': 2}
>>> foo(d1, d2)
>>> print (d1, d2)
({'value': 2}, {'value': 3})
``` |
10,621,021 | I am a newbie to python,everywhere I read about list methods I see one thing
**The slice method returns a "new" list**
What is here meant by "new" list,and why is it faster then changing the original list?
Does it really matter if python manipulates the original list,I mean I cant use it anyway. | 2012/05/16 | [
"https://Stackoverflow.com/questions/10621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1251851/"
] | I hope that this helps explain what it means by making a new list:
```
>>> lista = [1, 2, 3, 4]
>>> listb = lista
>>> print lista
[1, 2, 3, 4]
>>> print listb
[1, 2, 3, 4]
>>> lista[0] = 3
>>> print listb
[3, 2, 3, 4]
>>> listc = lista[:]
>>> print listc
[3, 2, 3, 4]
>>> lista[0] = 1
>>> print listc
[3, 2, 3, 4]
```
When doing `listb = lista` you are not making a new list, you are making an additional reference to the same list. This is shown by changing the first element in lista with `lista[0] = 3`, this also changes the first element in listb. However, when slicing lista into listc with `listc = lista[:]` you are copying over the values. When changing the first element of lista back to 1 with `lista[0] = 1`, the first element of listc is still 3.
For speed I would expect slicing to be slower but this should **not** be a consideration for which one to use. As I've shown they both have a very different implication and it depends on what you are going to do with the list, rather than on speed (*this is in general. There are occasion where the speed might be important*). | With lists, you can do both:
1) create a new list (the original is left intact):
```
In [1]: l = [1, 2, 3, 4, 5]
In [2]: l[:3]
Out[2]: [1, 2, 3]
In [3]: l
Out[3]: [1, 2, 3, 4, 5]
```
2) modify the list in-place:
```
In [6]: del l[3:]
In [7]: l
Out[7]: [1, 2, 3]
In [8]: l.append(15)
In [9]: l
Out[9]: [1, 2, 3, 15]
```
It's up to you to choose which way makes more sense for your problem.
In contrast to lists, tuples are immutable, which means that you can slice them, but you cannot modify them in place. |
10,621,021 | I am a newbie to python,everywhere I read about list methods I see one thing
**The slice method returns a "new" list**
What is here meant by "new" list,and why is it faster then changing the original list?
Does it really matter if python manipulates the original list,I mean I cant use it anyway. | 2012/05/16 | [
"https://Stackoverflow.com/questions/10621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1251851/"
] | With lists, you can do both:
1) create a new list (the original is left intact):
```
In [1]: l = [1, 2, 3, 4, 5]
In [2]: l[:3]
Out[2]: [1, 2, 3]
In [3]: l
Out[3]: [1, 2, 3, 4, 5]
```
2) modify the list in-place:
```
In [6]: del l[3:]
In [7]: l
Out[7]: [1, 2, 3]
In [8]: l.append(15)
In [9]: l
Out[9]: [1, 2, 3, 15]
```
It's up to you to choose which way makes more sense for your problem.
In contrast to lists, tuples are immutable, which means that you can slice them, but you cannot modify them in place. | 1. "new" means a shallow copy of the portion of the list you sliced.
2. It depends on what you are trying to do. For your particular implementation, you might not care about the original data, but I'm sure you could come up with scenarios where you want to work with a subset of data without modifying the originals (though do keep in mind it is only a shallow copy, so there are many instances where you will be modifying the data in the original and slice when working on a slice). Also, it's not faster; in fact, it's actually slower, since the system needs to allocate memory and construct new objects. The gain is not speed, but functionality. |
10,621,021 | I am a newbie to python,everywhere I read about list methods I see one thing
**The slice method returns a "new" list**
What is here meant by "new" list,and why is it faster then changing the original list?
Does it really matter if python manipulates the original list,I mean I cant use it anyway. | 2012/05/16 | [
"https://Stackoverflow.com/questions/10621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1251851/"
] | With lists, you can do both:
1) create a new list (the original is left intact):
```
In [1]: l = [1, 2, 3, 4, 5]
In [2]: l[:3]
Out[2]: [1, 2, 3]
In [3]: l
Out[3]: [1, 2, 3, 4, 5]
```
2) modify the list in-place:
```
In [6]: del l[3:]
In [7]: l
Out[7]: [1, 2, 3]
In [8]: l.append(15)
In [9]: l
Out[9]: [1, 2, 3, 15]
```
It's up to you to choose which way makes more sense for your problem.
In contrast to lists, tuples are immutable, which means that you can slice them, but you cannot modify them in place. | When a function/method create a new list, it means that your script has to consume the double amount of memory and has a little (or not so little) overhead while creating a duplicate of the old list.
If the list is really big, the performance of your script can drop very fast. That's why changing lists in-place is preferred when you have large amounts of data. |
10,621,021 | I am a newbie to python,everywhere I read about list methods I see one thing
**The slice method returns a "new" list**
What is here meant by "new" list,and why is it faster then changing the original list?
Does it really matter if python manipulates the original list,I mean I cant use it anyway. | 2012/05/16 | [
"https://Stackoverflow.com/questions/10621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1251851/"
] | I hope that this helps explain what it means by making a new list:
```
>>> lista = [1, 2, 3, 4]
>>> listb = lista
>>> print lista
[1, 2, 3, 4]
>>> print listb
[1, 2, 3, 4]
>>> lista[0] = 3
>>> print listb
[3, 2, 3, 4]
>>> listc = lista[:]
>>> print listc
[3, 2, 3, 4]
>>> lista[0] = 1
>>> print listc
[3, 2, 3, 4]
```
When doing `listb = lista` you are not making a new list, you are making an additional reference to the same list. This is shown by changing the first element in lista with `lista[0] = 3`, this also changes the first element in listb. However, when slicing lista into listc with `listc = lista[:]` you are copying over the values. When changing the first element of lista back to 1 with `lista[0] = 1`, the first element of listc is still 3.
For speed I would expect slicing to be slower but this should **not** be a consideration for which one to use. As I've shown they both have a very different implication and it depends on what you are going to do with the list, rather than on speed (*this is in general. There are occasion where the speed might be important*). | 1. "new" means a shallow copy of the portion of the list you sliced.
2. It depends on what you are trying to do. For your particular implementation, you might not care about the original data, but I'm sure you could come up with scenarios where you want to work with a subset of data without modifying the originals (though do keep in mind it is only a shallow copy, so there are many instances where you will be modifying the data in the original and slice when working on a slice). Also, it's not faster; in fact, it's actually slower, since the system needs to allocate memory and construct new objects. The gain is not speed, but functionality. |
10,621,021 | I am a newbie to python,everywhere I read about list methods I see one thing
**The slice method returns a "new" list**
What is here meant by "new" list,and why is it faster then changing the original list?
Does it really matter if python manipulates the original list,I mean I cant use it anyway. | 2012/05/16 | [
"https://Stackoverflow.com/questions/10621021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1251851/"
] | I hope that this helps explain what it means by making a new list:
```
>>> lista = [1, 2, 3, 4]
>>> listb = lista
>>> print lista
[1, 2, 3, 4]
>>> print listb
[1, 2, 3, 4]
>>> lista[0] = 3
>>> print listb
[3, 2, 3, 4]
>>> listc = lista[:]
>>> print listc
[3, 2, 3, 4]
>>> lista[0] = 1
>>> print listc
[3, 2, 3, 4]
```
When doing `listb = lista` you are not making a new list, you are making an additional reference to the same list. This is shown by changing the first element in lista with `lista[0] = 3`, this also changes the first element in listb. However, when slicing lista into listc with `listc = lista[:]` you are copying over the values. When changing the first element of lista back to 1 with `lista[0] = 1`, the first element of listc is still 3.
For speed I would expect slicing to be slower but this should **not** be a consideration for which one to use. As I've shown they both have a very different implication and it depends on what you are going to do with the list, rather than on speed (*this is in general. There are occasion where the speed might be important*). | When a function/method create a new list, it means that your script has to consume the double amount of memory and has a little (or not so little) overhead while creating a duplicate of the old list.
If the list is really big, the performance of your script can drop very fast. That's why changing lists in-place is preferred when you have large amounts of data. |
62,833,614 | I am working on a project with OpenCV and python but stuck on this small problem.
I have end-points' coordinates on many lines stored in a list. Sometimes a case is appearing that from a single point, more than one line is detected. From among these lines, I want to keep the line of shortest length and eliminate all the other lines thus my image will contain no point from where more than one line is drawn.
My variable which stores the information(coordinates of both the end-points) of all the lines initially detected is as follows:
```
var = [[Line1_EndPoint1, Line1_EndPoint2],
[Line2_EndPoint1, Line2_EndPoint2],
[Line3_EndPoint1, Line3_EndPoint2],
[Line4_EndPoint1, Line4_EndPoint2],
[Line5_EndPoint1, Line5_EndPoint2]]
```
where, LineX\_EndPointY(line number "X", endpoint "Y" of that line) is of type [x, y] where x and y are the coordinates of that point in the image.
Can someone suggest me how to solve this problem.
**You can modify the way data of the lines are stored. If you modify, please explain your data structure and how it is created**
Example of such data:
```
[[[551, 752], [541, 730]],
[[548, 738], [723, 548]],
[[285, 682], [226, 676]],
[[416, 679], [345, 678]],
[[345, 678], [388, 674]],
[[249, 679], [226, 676]],
[[270, 678], [388, 674]],
[[472, 650], [751, 473]],
[[751, 473], [716, 561]],
[[731, 529], [751, 473]]]
```
Python code would be appreciable. | 2020/07/10 | [
"https://Stackoverflow.com/questions/62833614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11651779/"
] | I still having the same problems
```
@EnableIntegration
@Configuration
@TestPropertySource(locations="classpath:/msc-test.properties")
@Slf4j
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@ContextConfiguration(classes = MessagingListenerTestConfig.class)
@Import(TestChannelBinderConfiguration.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@DirtiesContext
public class MessagingListenerTest {
@Autowired
private MessagingListener listener;
@Autowired
private InputDestination inputDestination;
@Autowired
private OutputDestination outputDestination;
@Mock
private RestTemplate restTemplate;
private static final String EXPECTED_URL = "http://localhost:11000/test/v2/verification/messaging";
@Before
public void setup() {
restTemplate = mock(RestTemplate.class);
ReflectionTestUtils.setField(listener, "restTemplate", restTemplate);
ResponseEntity<String> mockResponse = new ResponseEntity<>("{}", HttpStatus.ACCEPTED);
when(restTemplate.postForEntity(any(), any(), eq(String.class))).thenReturn(mockResponse);
}
@Test
public void testHundleMessage() {
JSONObject obj1 = new JSONObject()
.put("id", 1)
.put("targetClass", "/test/v2/verification");
Message<String> request = MessageBuilder.withPayload(obj1.toString()).build();
log.info("request Test : "+ request.getPayload());
inputDestination.send(new GenericMessage<byte[]>(request.getPayload().getBytes(StandardCharsets.UTF_8)));
listener.handle(request);
//Verificar la url del restTemplate
Mockito.verify(restTemplate, Mockito.times(1)).postForEntity(eq(EXPECTED_URL), any(), eq(String.class));
//Verificar la recepción de los mensajes
assertThat(outputDestination.receive()).isNotNull();
assertThat(outputDestination.receive().getPayload().toString()).contains("topicName");
}
}
```
**just in this line**
```
inputDestination.send(new GenericMessage<byte[]>(request.getPayload().getBytes(StandardCharsets.UTF_8)));
```
**and this the error Junit**
```
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at org.springframework.cloud.stream.binder.test.AbstractDestination.getChannel(AbstractDestination.java:34)
at org.springframework.cloud.stream.binder.test.InputDestination.send(InputDestination.java:37)
at com.common.messaging.MessagingListenerTest.testHundleMessage(MessagingListenerTest.java:93)
```
**and the console error**
```
2020-07-14 11:29:16.850 INFO 25240 --- [ main] c.b.a.m.c.m.MessagingListenerTest : The following profiles are active: test
2020-07-14 11:29:18.171 INFO 25240 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
2020-07-14 11:29:18.192 INFO 25240 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
2020-07-14 11:29:18.212 INFO 25240 --- [ main] faultConfiguringBeanFactoryPostProcessor : No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
2020-07-14 11:29:18.392 INFO 25240 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'integrationChannelResolver' of type [org.springframework.integration.support.channel.BeanFactoryChannelResolver] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-07-14 11:29:18.429 INFO 25240 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'integrationDisposableAutoCreatedBeans' of type [org.springframework.integration.config.annotation.Disposables] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-07-14 11:29:20.113 INFO 25240 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler'
2020-07-14 11:29:20.356 INFO 25240 --- [ main] o.s.i.e.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2020-07-14 11:29:20.358 INFO 25240 --- [ main] o.s.i.c.PublishSubscribeChannel : Channel 'application.errorChannel' has 1 subscriber(s).
2020-07-14 11:29:20.361 INFO 25240 --- [ main] o.s.i.e.EventDrivenConsumer : started bean '_org.springframework.integration.errorLogger'
2020-07-14 11:29:20.382 INFO 25240 --- [ main] c.b.a.m.c.m.MessagingListenerTest : Started MessagingListenerTest in 4.629 seconds (JVM running for 9.331)
2020-07-14 11:29:23.255 INFO 25240 --- [ main] c.b.a.m.c.m.MessagingListenerTest : request Test : {"targetClass":"/test/v2/verification","id":1}
2020-07-14 11:29:28.207 INFO 25240 --- [ main] o.s.i.e.EventDrivenConsumer : Removing {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2020-07-14 11:29:28.207 INFO 25240 --- [ main] o.s.i.c.PublishSubscribeChannel : Channel 'application.errorChannel' has 0 subscriber(s).
2020-07-14 11:29:28.207 INFO 25240 --- [ main] o.s.i.e.EventDrivenConsumer : stopped bean '_org.springframework.integration.errorLogger'
2020-07-14 11:29:28.208 INFO 25240 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'taskScheduler'
Picked up JAVA_TOOL_OPTIONS: -agentpath:"C:\windows\system32\Aternity\Java\JavaHookLoader.dll"="C:\ProgramData\Aternity\hooks"
```
**what could be the problem** | I think the problem is that you are calling `outputDestination.receive()` two times. First time you are getting the message and when trying to reach it second time it's not there.
For me was working this approach:
```
String messagePayload = new String(outputDestination.receive().getPayload());
assertThat(messagePayload).contains("topicName");
``` |
25,572,574 | Hello I've installed a local version of pip using
```
python get-pip.py --user
```
After that I can't find the path of pip, so I run:
```
python -m pip install --user Cython
```
Finally I can't import Cython
```
import Cython
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'Cython'
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25572574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486641/"
] | You need to filter each date field individually within the range, like so:
```
WHERE
(Date1 >= ISNULL(@DateFrom,'17531231')
AND Date1 <= ISNULL(@dateTo,'20991231'))
OR
(Date2 >= ISNULL(@DateFrom,'1753-12-31')
AND Date2 <= ISNULL(@dateTo,'20991231'))
OR
(Date3 >= ISNULL(@DateFrom,'1753-12-31')
AND Date3 <= ISNULL(@dateTo,'20991231'))
```
Otherwise you aren't checking the range for each date field, just that a date in that row matches one of the criteria. | Just for another way to look at it. This solution would also work. It makes the where clause simpler at the expense of an additional block of code and a join.
```
CREATE TABLE #dates (id INT, date1 DATE, date2 DATE, date3 DATE)
INSERT INTO #dates
VALUES
('1','12/13/1945','11/4/1930',NULL),
('2','9/12/1970','9/13/1971','9/14/1972'),
('3',NULL,NULL,NULL),
('4','1/1/2000','1/1/2001','1/1/2002')
DECLARE
@dateFrom datetime = '1940-01-01',
@dateTo datetime = '1950-01-01'
;WITH dateFilter AS (
SELECT id,[Date],DateIndex
FROM
(SELECT
id, date1, date2, date3
FROM #dates) p
UNPIVOT([DATE] FOR DateIndex IN ([date1],[date2],[date3])) AS up
WHERE
up.[DATE] BETWEEN @dateFrom AND @dateTo
)
SELECT
d.*
FROM #dates d
INNER JOIN dateFilter df
ON df.id = d.id
DROP TABLE #dates
``` |
25,572,574 | Hello I've installed a local version of pip using
```
python get-pip.py --user
```
After that I can't find the path of pip, so I run:
```
python -m pip install --user Cython
```
Finally I can't import Cython
```
import Cython
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'Cython'
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25572574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486641/"
] | You need to filter each date field individually within the range, like so:
```
WHERE
(Date1 >= ISNULL(@DateFrom,'17531231')
AND Date1 <= ISNULL(@dateTo,'20991231'))
OR
(Date2 >= ISNULL(@DateFrom,'1753-12-31')
AND Date2 <= ISNULL(@dateTo,'20991231'))
OR
(Date3 >= ISNULL(@DateFrom,'1753-12-31')
AND Date3 <= ISNULL(@dateTo,'20991231'))
```
Otherwise you aren't checking the range for each date field, just that a date in that row matches one of the criteria. | Ok this is simplistic but it would work I think since it is in a proc...
declare @startDate datetimne
declare @enddate datetime
if @datefrom is NULL
set @startDate = '12/31/1753'
else
set @startDate = @datefrom
if @dateTo is NULL
set @endDate = '12/31/2099'
else
set @endDate = @dateto
and use @datefrom and @dateto to qualify... |
25,572,574 | Hello I've installed a local version of pip using
```
python get-pip.py --user
```
After that I can't find the path of pip, so I run:
```
python -m pip install --user Cython
```
Finally I can't import Cython
```
import Cython
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'Cython'
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25572574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486641/"
] | Just for another way to look at it. This solution would also work. It makes the where clause simpler at the expense of an additional block of code and a join.
```
CREATE TABLE #dates (id INT, date1 DATE, date2 DATE, date3 DATE)
INSERT INTO #dates
VALUES
('1','12/13/1945','11/4/1930',NULL),
('2','9/12/1970','9/13/1971','9/14/1972'),
('3',NULL,NULL,NULL),
('4','1/1/2000','1/1/2001','1/1/2002')
DECLARE
@dateFrom datetime = '1940-01-01',
@dateTo datetime = '1950-01-01'
;WITH dateFilter AS (
SELECT id,[Date],DateIndex
FROM
(SELECT
id, date1, date2, date3
FROM #dates) p
UNPIVOT([DATE] FOR DateIndex IN ([date1],[date2],[date3])) AS up
WHERE
up.[DATE] BETWEEN @dateFrom AND @dateTo
)
SELECT
d.*
FROM #dates d
INNER JOIN dateFilter df
ON df.id = d.id
DROP TABLE #dates
``` | Ok this is simplistic but it would work I think since it is in a proc...
declare @startDate datetimne
declare @enddate datetime
if @datefrom is NULL
set @startDate = '12/31/1753'
else
set @startDate = @datefrom
if @dateTo is NULL
set @endDate = '12/31/2099'
else
set @endDate = @dateto
and use @datefrom and @dateto to qualify... |
26,569,498 | I am new to python. I want to store each HTML tag into item of list.
```
from bs4 import BeautifulSoup
text = """
<body>
<div class="product">
<div class="x">orange</div>
<div class="x">apple</div>
<p> This is text </p>
</div>
</body>"""
soup = BeautifulSoup(text)
y=[]
for i in (soup.find_all("div", class_="product")):
y.append(i.get_text().encode("utf-8").strip())
```
From the above code the length of y is 1 and store all text on one item of list. However,it is necessary to parse using "div product" and store each text inside html tag into different item to list.
So the y will be :
```
y =['orange', 'apple', 'This is text']
```
instead of :
```
y=['orange\napple\n This is text']
``` | 2014/10/26 | [
"https://Stackoverflow.com/questions/26569498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2291434/"
] | Assuming your HTML code looks something like this:
```
<ul class="ulComprar">
<li>Milk</li>
<li class="liEspecial">Eggs</li>
<li>Bread</li>
</ul>
```
Then you could use the following query snippet to show and hide element li.liEspecial:
```
$('.ulComprar').hover(
function() {
$('.liEspecial', this).hide(); // hides li on mouse enter
}, function() {
$('.liEspecial', this).show(); // shows li on mouse leave
}
);
``` | we don't have `display: normal;`. the default `display` for [li](http://www.w3schools.com/tags/tag_li.asp) is `list-item`. try this code:
```
$('.ulComprar').on('mouseenter', function () {
$('.liEspecial').css("display", "list-item");
}).on('mouseleave', function () {
$('.liEspecial').css("display", "none");
});
```
[jsfiddle](http://jsfiddle.net/yhhoL6ce/1/) |
36,306,938 | I want to generate colors that go well with a given `UIColor` (Triadic, Analogues, Complement etc).
I have read a lot of posts like [this](https://stackoverflow.com/questions/14095849/calculating-the-analogous-color-with-python/14116553#14116553) and [this](https://stackoverflow.com/questions/180/function-for-creating-color-wheels) and [this](https://stackoverflow.com/questions/4235072/math-behind-the-colour-wheel). In the last post, The answerer suggested going to easyrgb.com.
So I went there. I learnt that I need to "rotate" the hue by some degrees if I want to generate those color schemes. For example, for Triadic colors, I need to rotate it by ± 120 degrees.
I know that I can get a color's hue by calling `getHue(:saturation:brightness:)`, but how can I "rotate" it? Isn't the hue returned by the method a number? A number between 0 and 1? This makes no sense to me!
I think the first post might have the answer but the code is written in python. I only learnt a little bit of python so I don't quite know what this means:
```
h = [(h+d) % 1 for d in (-d, d)] # Rotation by d
```
From the comment, I see that this line somehow rotates the hue by d degrees. But I don't know what that syntax means.
Can anyone tell me how to rotate the hue, or translate the above code to swift? | 2016/03/30 | [
"https://Stackoverflow.com/questions/36306938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5133585/"
] | The hue component ranges from 0.0 to 1.0, which corresponds to the angle from 0º to 360º in a color wheel (compare [Wikipedia: HSL and HSV](http://en.wikipedia.org/wiki/HSL_and_HSV)).
To "rotate" the hue component by `n` degrees, use:
```
let n = 120 // 120 degrees as an example
hue = fmod(hue + CGFloat(n)/360.0, 1.0)
```
The `fmod()` function is used to normalize the result of
the addition to the range 0.0 to 1.0.
The hue for the complementary color would be
```
let hueComplement = fmod(hue + 0.5, 1.0)
``` | >
> **In SwiftUI you can do by using apple documentation code**
>
>
>
```
struct HueRotation: View {
var body: some View {
HStack {
ForEach(0..<6) {
Rectangle()
.fill(.linearGradient(
colors: [.blue, .red, .green],
startPoint: .top, endPoint: .bottom))
.hueRotation((.degrees(Double($0 * 36))))
.frame(width: 60, height: 60, alignment: .center)
}
}
}
```
} |
70,298,164 | I have this python coded statement:
```
is_headless = ["--headless"] if sys.argv[0].find('console.py') != -1 else [""]
```
1. In what way does the blank between `["--headless"]` and `if` control the code line?
2. How and would `"--headless"` ever be an element in the `is_headless` variable?
3. Using the variable name `is_headless` suggests the final value would
be `True` or `False`. Is this correct thinking? In what case would `True` or `False` be assigned?
4. Is `[""]` a way to indicate `False`?
5. A little confused... | 2021/12/09 | [
"https://Stackoverflow.com/questions/70298164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17640238/"
] | There is not much to it. Just increment the pointer. → `p++`
```
void printArray(int *s_ptr, int *e_ptr) {
for (int *p = s_ptr; p <= e_ptr; p++) {
printf("%d\n", *p);
}
}
``` | >
> *How can I can print the whole array using only the addreses of the first element and the last element?*
>
>
>
To start with, couple of things about array that you should know (if not aware of):
1. An array is a collection of elements of the same type placed in **contiguous memory locations**.
2. An array name, when used in an expression, **will convert to pointer to first element of that array** (there are few *exceptions* to this rule).
E.g.:
```
#include <stdio.h>
int main (void) {
int arr[] = {1, 2, 3, 4, 5};
// Hardcoding the size of array (5) in for loop condition
// Note that you can use expression - sizeof (arr) / sizeof (arr[0]) to get size
// of array instead of hardcoding it.
for (size_t i = 0; i < 5; ++i) {
printf ("%d\n", arr[i]);
}
return 0;
}
```
Here the `arr[i]`, in `printf()` statement, will be interpreted as1) -
```
(*((arr) + (i)))
```
and, in this expression, the `arr` will be converted to address of first element of array `arr` i.e. `&arr[0]` and to that address the value of `i` will be added and the resultant pointer will be then dereferenced to get the value at that location. Since, the array element placed in contiguous memory locations, adding `0`, `1`, `2`, .., and so on, to the address of first element of array and dereferencing it will give the value of `1`st, `2`nd, `3`rd, .., and so on, elements of array respectively.
Now, you are passing the address of first and last element of given array to function `printArray()`. Using the address of first element we can get the value of all the elements of array. The only thing we need is the size of array in `printArray()` function.
From C Standard#6.5.6p9 *[emphasis added]*
>
> **When two pointers are subtracted, both shall point to elements of the same array object**, or one past the last element of the array object; **the result is the difference of the subscripts of the two array elements**. The size of the result is implementation-defined, and **its type (a signed integer type) is ptrdiff\_t** defined in the <stddef.h> header.
>
>
>
The two argument to `printArray()` function are pointer to first and last element of same array. As you have shown in question, the `printArray()` is called like this:
```
printArray(&array[0], &array[MaxSize-1]);
^ ^^^^^^^^^
| |
subscript subscript
of first of last
element element
```
When we subtract them the result we get is the difference of the subscripts of the first and last elements of that array. That means, in `printArray()` function() this
```
e_ptr - s_ptr
```
will give result same as
```
MaxSize-1 - 0 = MaxSize-1
```
if we add one to this result, we will get size of array
```
MaxSize-1 + 1 = MaxSize
```
Now, we know how to get size of array in `printArray()` and also know how to get the value of all elements of array using the address of first element. Lets implement `printArray()`:
```
void printArray(int *s_ptr, int *e_ptr) {
// To get the size of array subtract e_ptr and s_ptr and add 1
ptrdiff_t size = e_ptr - s_ptr + 1;
for (ptrdiff_t i = 0; i < size; ++i) {
printf ("%d\n", *((s_ptr) + (i)));
}
}
```
This will output all the elements of array, provided `s_ptr` should be pointer to first element and `e_ptr` should be pointer to last element of same array. This `*((s_ptr) + (i))` looks bit cluttered. As per the definition of subscript operator `[]`1), `*((s_ptr) + (i))` is same as `s_ptr[i]`. So, the `printf()` statement in the for loop can be written as - `printf ("%d\n", s_ptr[i]);`.
Alternatively, you can use the pointer of type same as type of array element. Assign the first element address to this pointer and dereferencing it to get value at that location. Increment the pointer and print till it reaches to address of last element of array. The implementation is shown in *@Cheatah* post.
---
1). C11 standard##6.5.2.1p2
>
> The definition of the subscript operator [] is that E1[E2] is identical to (\*((E1)+(E2)))
>
>
> |
12,193,803 | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to specify the "no cache" option from the command line directly? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12193803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605337/"
] | I suggest that you press Ctrl+F5 when refreshing the browser.
Just ran into [this](https://gist.github.com/3300372), it can just might be the thing you are looking for (it's in ruby, by the way) | Maybe it's the browser caching your files not the SimpleHTTPServer. Try deactivating the browser cache first. |
12,193,803 | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to specify the "no cache" option from the command line directly? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12193803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605337/"
] | Perhaps this may work. Save the following to a file:
**serveit.py**
```
#!/usr/bin/env python
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.send_header("Pragma", "no-cache")
self.send_header("Expires", "0")
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
```
then run it using
```
python serveit.py 8000
```
to serve the current directory on port 8000. This was totally pulled [from this gist](https://gist.github.com/dustingetz/5348582), and seems to work great!
NOTE: If you're just looking to run a local webserver to serve static content, you may be interested in a [precanned node solution to do this => http-server](https://github.com/indexzero/http-server), which I've been using and seems to work great.
Also if you're on a mac, if you run this as root you can run it on port 80 or 443! For example
`sudo python serveit.py 80`
should allow you to run it and access it in your browser at `http://localhost` | Maybe it's the browser caching your files not the SimpleHTTPServer. Try deactivating the browser cache first. |
12,193,803 | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to specify the "no cache" option from the command line directly? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12193803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605337/"
] | Of course the script above will not work for Python 3.x, but it just consists of changing the `SimpleHTTPServer` to `http.server` as shown below:
```
#!/usr/bin/env python3
import http.server
class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
http.server.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.send_header("Pragma", "no-cache")
self.send_header("Expires", "0")
if __name__ == '__main__':
http.server.test(HandlerClass=MyHTTPRequestHandler)
``` | Maybe it's the browser caching your files not the SimpleHTTPServer. Try deactivating the browser cache first. |
12,193,803 | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to specify the "no cache" option from the command line directly? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12193803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605337/"
] | Maybe it's the browser caching your files not the SimpleHTTPServer. Try deactivating the browser cache first. | I changed to another port number and the updated file reflected on my browser.
ex.
```py
python -m http.server -p 8000
python -m http.server -p 8001
``` |
12,193,803 | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to specify the "no cache" option from the command line directly? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12193803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605337/"
] | Perhaps this may work. Save the following to a file:
**serveit.py**
```
#!/usr/bin/env python
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.send_header("Pragma", "no-cache")
self.send_header("Expires", "0")
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
```
then run it using
```
python serveit.py 8000
```
to serve the current directory on port 8000. This was totally pulled [from this gist](https://gist.github.com/dustingetz/5348582), and seems to work great!
NOTE: If you're just looking to run a local webserver to serve static content, you may be interested in a [precanned node solution to do this => http-server](https://github.com/indexzero/http-server), which I've been using and seems to work great.
Also if you're on a mac, if you run this as root you can run it on port 80 or 443! For example
`sudo python serveit.py 80`
should allow you to run it and access it in your browser at `http://localhost` | I suggest that you press Ctrl+F5 when refreshing the browser.
Just ran into [this](https://gist.github.com/3300372), it can just might be the thing you are looking for (it's in ruby, by the way) |
12,193,803 | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to specify the "no cache" option from the command line directly? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12193803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605337/"
] | I suggest that you press Ctrl+F5 when refreshing the browser.
Just ran into [this](https://gist.github.com/3300372), it can just might be the thing you are looking for (it's in ruby, by the way) | I changed to another port number and the updated file reflected on my browser.
ex.
```py
python -m http.server -p 8000
python -m http.server -p 8001
``` |
12,193,803 | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to specify the "no cache" option from the command line directly? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12193803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605337/"
] | Perhaps this may work. Save the following to a file:
**serveit.py**
```
#!/usr/bin/env python
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.send_header("Pragma", "no-cache")
self.send_header("Expires", "0")
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
```
then run it using
```
python serveit.py 8000
```
to serve the current directory on port 8000. This was totally pulled [from this gist](https://gist.github.com/dustingetz/5348582), and seems to work great!
NOTE: If you're just looking to run a local webserver to serve static content, you may be interested in a [precanned node solution to do this => http-server](https://github.com/indexzero/http-server), which I've been using and seems to work great.
Also if you're on a mac, if you run this as root you can run it on port 80 or 443! For example
`sudo python serveit.py 80`
should allow you to run it and access it in your browser at `http://localhost` | Of course the script above will not work for Python 3.x, but it just consists of changing the `SimpleHTTPServer` to `http.server` as shown below:
```
#!/usr/bin/env python3
import http.server
class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
http.server.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.send_header("Pragma", "no-cache")
self.send_header("Expires", "0")
if __name__ == '__main__':
http.server.test(HandlerClass=MyHTTPRequestHandler)
``` |
12,193,803 | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to specify the "no cache" option from the command line directly? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12193803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605337/"
] | Perhaps this may work. Save the following to a file:
**serveit.py**
```
#!/usr/bin/env python
import SimpleHTTPServer
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.send_header("Pragma", "no-cache")
self.send_header("Expires", "0")
if __name__ == '__main__':
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler)
```
then run it using
```
python serveit.py 8000
```
to serve the current directory on port 8000. This was totally pulled [from this gist](https://gist.github.com/dustingetz/5348582), and seems to work great!
NOTE: If you're just looking to run a local webserver to serve static content, you may be interested in a [precanned node solution to do this => http-server](https://github.com/indexzero/http-server), which I've been using and seems to work great.
Also if you're on a mac, if you run this as root you can run it on port 80 or 443! For example
`sudo python serveit.py 80`
should allow you to run it and access it in your browser at `http://localhost` | I changed to another port number and the updated file reflected on my browser.
ex.
```py
python -m http.server -p 8000
python -m http.server -p 8001
``` |
12,193,803 | On Windows 7, I am using the command line
```
python -m SimpleHTTPServer 8888
```
to invoke a simple web server to serve files from a directory, for development.
The problem is that the server seems to keep the files in cache. Old versions of files are served despite newer ones being available.
Is there a way to specify the "no cache" option from the command line directly? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12193803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605337/"
] | Of course the script above will not work for Python 3.x, but it just consists of changing the `SimpleHTTPServer` to `http.server` as shown below:
```
#!/usr/bin/env python3
import http.server
class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
http.server.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.send_header("Pragma", "no-cache")
self.send_header("Expires", "0")
if __name__ == '__main__':
http.server.test(HandlerClass=MyHTTPRequestHandler)
``` | I changed to another port number and the updated file reflected on my browser.
ex.
```py
python -m http.server -p 8000
python -m http.server -p 8001
``` |
10,361,714 | I mostly spend time on Python/Django and Objective-C/CocoaTouch and js/jQuery in the course of my daily work.
My editor of choice is `vim` for Python/Django and js/jQuery and `xcode` for Objective-C/CocoaTouch.
One of the bottlenecks on my development speed is the pace at which I read existing code, particularly open source libraries which I use.
In Python/Django for example, when I encounter some new features introduced by django developers, I get curious and begin exploring the code base manually. For example, when class-based views were introduced from django 1.3 onwards, reference - <https://docs.djangoproject.com/en/dev/topics/class-based-views/> - I will check out the example code shown:
```
from django.views.generic import TemplateView
class AboutView(TemplateView):
template_name = "about.html"
```
And try it out on one of my projects. More importantly, I am curious about what goes on behind the scenes, so I will dig into the source code -
```
# django/views/generic/__init__.py file
from django.views.generic.base import View, TemplateView, RedirectView
from django.views.generic.dates import (ArchiveIndexView, YearArchiveView, MonthArchiveView,
WeekArchiveView, DayArchiveView, TodayArchiveView,
DateDetailView)
from django.views.generic.detail import DetailView
from django.views.generic.edit import FormView, CreateView, UpdateView, DeleteView
from django.views.generic.list import ListView
class GenericViewError(Exception):
"""A problem in a generic view."""
pass
```
From here, I will trace it backwards to the django/views/generic/base.py file and find out exactly what `TemplateView` class does:-
```
class TemplateView(TemplateResponseMixin, View):
"""
A view that renders a template.
"""
def get_context_data(self, **kwargs):
return {
'params': kwargs
}
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
```
And here's it shows that `TemplateView` class inherits from `TemplateResponseMixin` and `View` classes... and I continue digging further... and so on...
**The problem is, this is an extremely inefficient and slow process (to "follow" class hierachies manually and opening up each file along the way).**
So the question is - is there an easy way/UI tool (or other visual solution) that parses Python code in a particular project and visualize class hierarchies which I can then inspect easily by "clicking" on a specific class I am interested to read about?
**Note** that I am aware of IPython shell but that doesn't seem as user-friendly as a visual display tool.
For example, there's `F-Script` in the world of Objective-C/iOS/Mac programming, which not only provides a shell (much like python or IPython shell), but provides a visual way for developers to introspect class hierachies.
Reference screenshot:-

So is there a class-hierarchy visualization tool (for Python specifically, but even better if it's generic and can be used for different languages)??? What are your methods of getting up to speed efficiently when reading open source source code???
**UPDATED**
Per advice below, I tried out `ctags` and vim plugin `taglist` and I was able to use `:TlistOpen` to open up a side buffer in vim like this:-

This looks really cool as `:TlistOpen` now essentially shows me all the classes and functions that are available on my currently open buffer.
My problem now is that when I attempt to do `Ctrl``]` while my cursor is on `TemplateView`, I get the following error:-

What am I doing wrong? Is it because my django source code is in a `virtualenv`? Or is there something specific I have to do to make `ctags`/`taglist` "aware" of the django source code? | 2012/04/28 | [
"https://Stackoverflow.com/questions/10361714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/482506/"
] | Tags are a very good start indeed. (There's too much stuff all over the place on it, so I'll just provide you with one extra keyword to search with: ctags.)
In Vim, it ends up (in the basic case) with `Ctrl+]` to go to a class/function definition and `Ctrl+T` to return. | I've been using [exuberant ctags](http://ctags.sourceforge.net/) with [taglist](http://www.vim.org/scripts/script.php?script_id=273) for vim. Use `ctrl``]` to jump to class definition in the current window, `ctrl``w``]` to jump to the definition in a split window.
You can install exuberant ctags via homebrew:
```
brew install ctags
```
Be sure to use the one installed at `/usr/local/bin` by homebrew, not the old `ctags` in `/usr/bin`.
It is also helpful to put `--python-kinds=-vi` in `~/.ctags` to skip indexing variables and imports for Python files.
Another alternative would be to use a variant of `cscope` or `pyscope` though you must have your vim compiled with `cscope` option enabled. |
10,361,714 | I mostly spend time on Python/Django and Objective-C/CocoaTouch and js/jQuery in the course of my daily work.
My editor of choice is `vim` for Python/Django and js/jQuery and `xcode` for Objective-C/CocoaTouch.
One of the bottlenecks on my development speed is the pace at which I read existing code, particularly open source libraries which I use.
In Python/Django for example, when I encounter some new features introduced by django developers, I get curious and begin exploring the code base manually. For example, when class-based views were introduced from django 1.3 onwards, reference - <https://docs.djangoproject.com/en/dev/topics/class-based-views/> - I will check out the example code shown:
```
from django.views.generic import TemplateView
class AboutView(TemplateView):
template_name = "about.html"
```
And try it out on one of my projects. More importantly, I am curious about what goes on behind the scenes, so I will dig into the source code -
```
# django/views/generic/__init__.py file
from django.views.generic.base import View, TemplateView, RedirectView
from django.views.generic.dates import (ArchiveIndexView, YearArchiveView, MonthArchiveView,
WeekArchiveView, DayArchiveView, TodayArchiveView,
DateDetailView)
from django.views.generic.detail import DetailView
from django.views.generic.edit import FormView, CreateView, UpdateView, DeleteView
from django.views.generic.list import ListView
class GenericViewError(Exception):
"""A problem in a generic view."""
pass
```
From here, I will trace it backwards to the django/views/generic/base.py file and find out exactly what `TemplateView` class does:-
```
class TemplateView(TemplateResponseMixin, View):
"""
A view that renders a template.
"""
def get_context_data(self, **kwargs):
return {
'params': kwargs
}
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
```
And here's it shows that `TemplateView` class inherits from `TemplateResponseMixin` and `View` classes... and I continue digging further... and so on...
**The problem is, this is an extremely inefficient and slow process (to "follow" class hierachies manually and opening up each file along the way).**
So the question is - is there an easy way/UI tool (or other visual solution) that parses Python code in a particular project and visualize class hierarchies which I can then inspect easily by "clicking" on a specific class I am interested to read about?
**Note** that I am aware of IPython shell but that doesn't seem as user-friendly as a visual display tool.
For example, there's `F-Script` in the world of Objective-C/iOS/Mac programming, which not only provides a shell (much like python or IPython shell), but provides a visual way for developers to introspect class hierachies.
Reference screenshot:-

So is there a class-hierarchy visualization tool (for Python specifically, but even better if it's generic and can be used for different languages)??? What are your methods of getting up to speed efficiently when reading open source source code???
**UPDATED**
Per advice below, I tried out `ctags` and vim plugin `taglist` and I was able to use `:TlistOpen` to open up a side buffer in vim like this:-

This looks really cool as `:TlistOpen` now essentially shows me all the classes and functions that are available on my currently open buffer.
My problem now is that when I attempt to do `Ctrl``]` while my cursor is on `TemplateView`, I get the following error:-

What am I doing wrong? Is it because my django source code is in a `virtualenv`? Or is there something specific I have to do to make `ctags`/`taglist` "aware" of the django source code? | 2012/04/28 | [
"https://Stackoverflow.com/questions/10361714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/482506/"
] | Tags are a very good start indeed. (There's too much stuff all over the place on it, so I'll just provide you with one extra keyword to search with: ctags.)
In Vim, it ends up (in the basic case) with `Ctrl+]` to go to a class/function definition and `Ctrl+T` to return. | The IDLE editor included with Python has [an effective class browser](http://hg.python.org/cpython/file/3bac1e1a0e0d/Lib/idlelib/ClassBrowser.py) that efficiently navigates everything in a given module. I believe in would not be difficult to modify that tool to navigate a full class-hierarchy with some assistance from the [inspect module](http://docs.python.org/library/inspect.html#module-inspect) and the [pyclbr module](http://docs.python.org/library/pyclbr.html#module-pyclbr). |
31,846,508 | I'm new in python and I'm trying to dynamically create new instances in a class. So let me give you an example, if I have a class like this:
```
class Person(object):
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
```
As far as I know, for each new instance I have to insert, I would have to declare a variable and attach it to the person object, something like this:
```
variable = Person(name, age, job)
```
Is there a way in which I can dynamically do this? Lets suppose that I have a dictionary like this:
```
persons_database = {
'id' : ['name', age, 'job'], .....
}
```
Can I create a piece of code that can iterate over this db and automatically create new instances in the `Person` class? | 2015/08/06 | [
"https://Stackoverflow.com/questions/31846508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5196412/"
] | Just iterate over the dictionary using a for loop.
```
people = []
for id in persons_database:
info = persons_database[id]
people.append(Person(info[0], info[1], info[2]))
```
Then the List `people` will have `Person` objects with the data from your persons\_database dictionary
If you need to get the Person object from the original id you can use a dictionary to store the Person objects and can quickly find the correct Person.
```
people = {}
for id, data in persons_database.items():
people[id] = Person(data[0], data[1], data[2])
```
Then you can get the person you want from his/her id by doing `people[id]`. So to increment a person with id = 1's age you would do `people[1].increment_age()`
------ Slightly more advanced material below ----------------
Some people have mentioned using list/dictionary comprehensions to achieve what you want. Comprehensions would be slightly more efficient and more pythonic, but a little more difficult to understand if you are new to programming/python
As a dictionary comprehension the second piece of code would be `people = {id: Person(*data) for id, data in persons_database.items()}`
And just so nothing here goes unexplained... The `*` before a List in python unpacks the List as separate items in the sequential order of the list, so for a List `l` of length n, `*l` would evaluate to `l[0], l[1], ... , l[n-2], l[n-1]` | Sure, a simple [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) should do the trick:
```
people = [Person(*persons_database[pid]) for pid in persons_database]
```
This just loops through each key (id) in the person database and creates a person instance by passing through the list of attributes for that id directly as args to the `Person()` constructor. |
3,580,520 | To add gtk-2.0 to my virtualenv I did the following:
```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
```
[Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-packages)
Now in the Python interpreter when I do import gtk it says: No module named gtk. When I start the interpreter with sudo it works.
Any reason why I need to use sudo and is there a way to prevent it?
**Update:**
Forgot to mention that cairo and pygtk work but it's not the one I need.
**Update2:**
Here the directory to show that I ain't crazy.
<http://www.friendly-stranger.com/pictures/symlink.jpg> | 2010/08/27 | [
"https://Stackoverflow.com/questions/3580520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145117/"
] | `sudo python` imports it just fine because that interpreter isn't using your virtual environment. So don't do that.
You only linked in one of the necessary items. Do the others mentioned in the answer to the question you linked as well.
(The pygtk.pth file is of particular importance, since it tells python to actually put that directory you linked onto the python path)
Update
------
Put that stuff in $VIRTUALENV/lib/python2.6/**site-packages/** rather than the directory above that.
Looks like the .pth files aren't read from that directory - just from site-packages | This works for me (Ubuntu 11.10):
once you activate your virtualenv directory make sure 'dist-packages' exists:
```
mkdir -p lib/python2.7/dist-packages/
```
Then, make links:
For GTK2:
```
ln -s /usr/lib/python2.7/dist-packages/glib/ lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/gobject/ lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/gtk-2.0* lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/pygtk.pth lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/cairo lib/python2.7/dist-packages/
```
For GTK3:
```
ln -s /usr/lib/python2.7/dist-packages/gi lib/python2.7/dist-packages/
``` |
3,580,520 | To add gtk-2.0 to my virtualenv I did the following:
```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
```
[Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-packages)
Now in the Python interpreter when I do import gtk it says: No module named gtk. When I start the interpreter with sudo it works.
Any reason why I need to use sudo and is there a way to prevent it?
**Update:**
Forgot to mention that cairo and pygtk work but it's not the one I need.
**Update2:**
Here the directory to show that I ain't crazy.
<http://www.friendly-stranger.com/pictures/symlink.jpg> | 2010/08/27 | [
"https://Stackoverflow.com/questions/3580520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145117/"
] | `sudo python` imports it just fine because that interpreter isn't using your virtual environment. So don't do that.
You only linked in one of the necessary items. Do the others mentioned in the answer to the question you linked as well.
(The pygtk.pth file is of particular importance, since it tells python to actually put that directory you linked onto the python path)
Update
------
Put that stuff in $VIRTUALENV/lib/python2.6/**site-packages/** rather than the directory above that.
Looks like the .pth files aren't read from that directory - just from site-packages | Remember to add a link to pygtk.py
```
ln -s /usr/lib/python2.7/dist-packages/pygtk.py lib/python2.7/dist-packages/
``` |
3,580,520 | To add gtk-2.0 to my virtualenv I did the following:
```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
```
[Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-packages)
Now in the Python interpreter when I do import gtk it says: No module named gtk. When I start the interpreter with sudo it works.
Any reason why I need to use sudo and is there a way to prevent it?
**Update:**
Forgot to mention that cairo and pygtk work but it's not the one I need.
**Update2:**
Here the directory to show that I ain't crazy.
<http://www.friendly-stranger.com/pictures/symlink.jpg> | 2010/08/27 | [
"https://Stackoverflow.com/questions/3580520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145117/"
] | `sudo python` imports it just fine because that interpreter isn't using your virtual environment. So don't do that.
You only linked in one of the necessary items. Do the others mentioned in the answer to the question you linked as well.
(The pygtk.pth file is of particular importance, since it tells python to actually put that directory you linked onto the python path)
Update
------
Put that stuff in $VIRTUALENV/lib/python2.6/**site-packages/** rather than the directory above that.
Looks like the .pth files aren't read from that directory - just from site-packages | On Debian based Linux systems (Ubuntu, Mint) you can just install the [ruamel.venvgtk](https://pypi.python.org/pypi/ruamel.venvgtk) package I put on PyPI. It will create the relevant links in your virtualenv during installation (if they are not yet there).
A more detailed explanation can be found in [this answer](https://stackoverflow.com/a/27471354/1307905) |
3,580,520 | To add gtk-2.0 to my virtualenv I did the following:
```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
```
[Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-packages)
Now in the Python interpreter when I do import gtk it says: No module named gtk. When I start the interpreter with sudo it works.
Any reason why I need to use sudo and is there a way to prevent it?
**Update:**
Forgot to mention that cairo and pygtk work but it's not the one I need.
**Update2:**
Here the directory to show that I ain't crazy.
<http://www.friendly-stranger.com/pictures/symlink.jpg> | 2010/08/27 | [
"https://Stackoverflow.com/questions/3580520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145117/"
] | `sudo python` imports it just fine because that interpreter isn't using your virtual environment. So don't do that.
You only linked in one of the necessary items. Do the others mentioned in the answer to the question you linked as well.
(The pygtk.pth file is of particular importance, since it tells python to actually put that directory you linked onto the python path)
Update
------
Put that stuff in $VIRTUALENV/lib/python2.6/**site-packages/** rather than the directory above that.
Looks like the .pth files aren't read from that directory - just from site-packages | If it is not a requirement, that Python system packages are not used in the virtual environment, I would install `apt install python-gtk2` (Ubuntu) and then create the virtual environment with:
`virtualenv --system-site-packages .`
That way, you do not pollute the system environment with your pip installations in the virtual environment, but reuse everything from the system. Especially pygtk. |
3,580,520 | To add gtk-2.0 to my virtualenv I did the following:
```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
```
[Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-packages)
Now in the Python interpreter when I do import gtk it says: No module named gtk. When I start the interpreter with sudo it works.
Any reason why I need to use sudo and is there a way to prevent it?
**Update:**
Forgot to mention that cairo and pygtk work but it's not the one I need.
**Update2:**
Here the directory to show that I ain't crazy.
<http://www.friendly-stranger.com/pictures/symlink.jpg> | 2010/08/27 | [
"https://Stackoverflow.com/questions/3580520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145117/"
] | This works for me (Ubuntu 11.10):
once you activate your virtualenv directory make sure 'dist-packages' exists:
```
mkdir -p lib/python2.7/dist-packages/
```
Then, make links:
For GTK2:
```
ln -s /usr/lib/python2.7/dist-packages/glib/ lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/gobject/ lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/gtk-2.0* lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/pygtk.pth lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/cairo lib/python2.7/dist-packages/
```
For GTK3:
```
ln -s /usr/lib/python2.7/dist-packages/gi lib/python2.7/dist-packages/
``` | Remember to add a link to pygtk.py
```
ln -s /usr/lib/python2.7/dist-packages/pygtk.py lib/python2.7/dist-packages/
``` |
3,580,520 | To add gtk-2.0 to my virtualenv I did the following:
```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
```
[Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-packages)
Now in the Python interpreter when I do import gtk it says: No module named gtk. When I start the interpreter with sudo it works.
Any reason why I need to use sudo and is there a way to prevent it?
**Update:**
Forgot to mention that cairo and pygtk work but it's not the one I need.
**Update2:**
Here the directory to show that I ain't crazy.
<http://www.friendly-stranger.com/pictures/symlink.jpg> | 2010/08/27 | [
"https://Stackoverflow.com/questions/3580520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145117/"
] | This works for me (Ubuntu 11.10):
once you activate your virtualenv directory make sure 'dist-packages' exists:
```
mkdir -p lib/python2.7/dist-packages/
```
Then, make links:
For GTK2:
```
ln -s /usr/lib/python2.7/dist-packages/glib/ lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/gobject/ lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/gtk-2.0* lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/pygtk.pth lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/cairo lib/python2.7/dist-packages/
```
For GTK3:
```
ln -s /usr/lib/python2.7/dist-packages/gi lib/python2.7/dist-packages/
``` | On Debian based Linux systems (Ubuntu, Mint) you can just install the [ruamel.venvgtk](https://pypi.python.org/pypi/ruamel.venvgtk) package I put on PyPI. It will create the relevant links in your virtualenv during installation (if they are not yet there).
A more detailed explanation can be found in [this answer](https://stackoverflow.com/a/27471354/1307905) |
3,580,520 | To add gtk-2.0 to my virtualenv I did the following:
```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
```
[Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-packages)
Now in the Python interpreter when I do import gtk it says: No module named gtk. When I start the interpreter with sudo it works.
Any reason why I need to use sudo and is there a way to prevent it?
**Update:**
Forgot to mention that cairo and pygtk work but it's not the one I need.
**Update2:**
Here the directory to show that I ain't crazy.
<http://www.friendly-stranger.com/pictures/symlink.jpg> | 2010/08/27 | [
"https://Stackoverflow.com/questions/3580520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145117/"
] | This works for me (Ubuntu 11.10):
once you activate your virtualenv directory make sure 'dist-packages' exists:
```
mkdir -p lib/python2.7/dist-packages/
```
Then, make links:
For GTK2:
```
ln -s /usr/lib/python2.7/dist-packages/glib/ lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/gobject/ lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/gtk-2.0* lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/pygtk.pth lib/python2.7/dist-packages/
ln -s /usr/lib/python2.7/dist-packages/cairo lib/python2.7/dist-packages/
```
For GTK3:
```
ln -s /usr/lib/python2.7/dist-packages/gi lib/python2.7/dist-packages/
``` | If it is not a requirement, that Python system packages are not used in the virtual environment, I would install `apt install python-gtk2` (Ubuntu) and then create the virtual environment with:
`virtualenv --system-site-packages .`
That way, you do not pollute the system environment with your pip installations in the virtual environment, but reuse everything from the system. Especially pygtk. |
3,580,520 | To add gtk-2.0 to my virtualenv I did the following:
```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
```
[Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-packages)
Now in the Python interpreter when I do import gtk it says: No module named gtk. When I start the interpreter with sudo it works.
Any reason why I need to use sudo and is there a way to prevent it?
**Update:**
Forgot to mention that cairo and pygtk work but it's not the one I need.
**Update2:**
Here the directory to show that I ain't crazy.
<http://www.friendly-stranger.com/pictures/symlink.jpg> | 2010/08/27 | [
"https://Stackoverflow.com/questions/3580520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145117/"
] | Remember to add a link to pygtk.py
```
ln -s /usr/lib/python2.7/dist-packages/pygtk.py lib/python2.7/dist-packages/
``` | On Debian based Linux systems (Ubuntu, Mint) you can just install the [ruamel.venvgtk](https://pypi.python.org/pypi/ruamel.venvgtk) package I put on PyPI. It will create the relevant links in your virtualenv during installation (if they are not yet there).
A more detailed explanation can be found in [this answer](https://stackoverflow.com/a/27471354/1307905) |
3,580,520 | To add gtk-2.0 to my virtualenv I did the following:
```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
```
[Virtualenv on Ubuntu with no site-packages](https://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-packages)
Now in the Python interpreter when I do import gtk it says: No module named gtk. When I start the interpreter with sudo it works.
Any reason why I need to use sudo and is there a way to prevent it?
**Update:**
Forgot to mention that cairo and pygtk work but it's not the one I need.
**Update2:**
Here the directory to show that I ain't crazy.
<http://www.friendly-stranger.com/pictures/symlink.jpg> | 2010/08/27 | [
"https://Stackoverflow.com/questions/3580520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145117/"
] | Remember to add a link to pygtk.py
```
ln -s /usr/lib/python2.7/dist-packages/pygtk.py lib/python2.7/dist-packages/
``` | If it is not a requirement, that Python system packages are not used in the virtual environment, I would install `apt install python-gtk2` (Ubuntu) and then create the virtual environment with:
`virtualenv --system-site-packages .`
That way, you do not pollute the system environment with your pip installations in the virtual environment, but reuse everything from the system. Especially pygtk. |
10,350,765 | Here is my basic problem:
I have a Python file with an import of
```
from math import sin,cos,sqrt
```
I need this file to still be 100% CPython compatible to allow my developers to write 100% CPython code and employ the great tools developed for Python.
Now enter Cython. In my Python file, the trig functions get called millions of times (fundamental to the code, can't change this). Is there any way that through some Python-fu in the main python file, or Cython magic otherwise I can instead use the C/C++ math functions using some variation on the Cython code
```
cdef extern from "math.h":
double sin(double)
```
That would give me near-C performance, which would be awesome.
[Stefan's talk](http://www.behnel.de/cython200910/talk.html) says specifically this can't be done, but the talk is two years old, and there are many creative people out there | 2012/04/27 | [
"https://Stackoverflow.com/questions/10350765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360263/"
] | I'm not a Cython expert, but AFAIK, all you could do is write a Cython wrapper around `sin` and call that. I can't imagine that's really going to be faster than `math.sin`, though, since it's still using Python calling semantics -- the overhead is in all the Python stuff to call the function, not the actual trig calculations, which are done in C when using CPython too.
Have you considered using [Cython pure mode](http://docs.cython.org/src/tutorial/pure.html), which makes the source CPython-compatible? | I may have misunderstood your problem, but the [Cython documentation on interfacing with external C code](http://docs.cython.org/src/userguide/external_C_code.html#resolving-naming-conflicts-c-name-specifications) seems to suggest the following syntax:
```
cdef extern from "math.h":
double c_sin "sin" (double)
```
which gives the function the name `sin` in the C code (so that it correctly links to the function from `math.h`), and `c_sin` in the Python module. I'm not really sure I understand what this achieves in this case, though - why would you want to use `math.sin` in Cython code? Do you have some statically typed variables, and some dynamically typed ones? |
10,350,765 | Here is my basic problem:
I have a Python file with an import of
```
from math import sin,cos,sqrt
```
I need this file to still be 100% CPython compatible to allow my developers to write 100% CPython code and employ the great tools developed for Python.
Now enter Cython. In my Python file, the trig functions get called millions of times (fundamental to the code, can't change this). Is there any way that through some Python-fu in the main python file, or Cython magic otherwise I can instead use the C/C++ math functions using some variation on the Cython code
```
cdef extern from "math.h":
double sin(double)
```
That would give me near-C performance, which would be awesome.
[Stefan's talk](http://www.behnel.de/cython200910/talk.html) says specifically this can't be done, but the talk is two years old, and there are many creative people out there | 2012/04/27 | [
"https://Stackoverflow.com/questions/10350765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360263/"
] | I'm not a Cython expert, but AFAIK, all you could do is write a Cython wrapper around `sin` and call that. I can't imagine that's really going to be faster than `math.sin`, though, since it's still using Python calling semantics -- the overhead is in all the Python stuff to call the function, not the actual trig calculations, which are done in C when using CPython too.
Have you considered using [Cython pure mode](http://docs.cython.org/src/tutorial/pure.html), which makes the source CPython-compatible? | Answering this question eight years later, this is what worked for me on Ubuntu 19.10 using the system CPython vesion 3.7.5 and Cython3 version 0.29.10 from the Ubuntu repostory.
The Cython documents on [Pure Python Mode](https://cython.readthedocs.io/en/latest/src/tutorial/pure.html) give an example that works. It looks a bit different to the examples in the old answers here so I guess the document has been updated since.
The Python file needs a *conditional* import, which works fine using normal CPython:
```none
#!/usr/bin/env python3
# from: https://cython.readthedocs.io/en/latest/src/tutorial/pure.html
# mymodule.py
import cython
# override with Python import if not in compiled code
if not cython.compiled:
from math import sin
# calls sin() from math.h when compiled with Cython and math.sin() in Python
print(sin(0.5))
```
The Cython language constructs must be put in a file with the same name but a ".pxd" suffix:
```none
#cython: language_level=3
# from: https://cython.readthedocs.io/en/latest/src/tutorial/pure.html
# mymodule.pxd
# declare a C function as "cpdef" to export it to the module
cdef extern from "math.h":
cpdef double sin(double x)
```
I used the "--embed" option to create C-code for a stand-alone Linux ELF executable to test this. The GCC compiler line needs "-lm" to import the maths module that contains sin.
```none
cython3 --embed mymodule.py
gcc -o mymodule mymodule.c -I/usr/include/python3.7 -lpython3.7m -lm
``` |
10,350,765 | Here is my basic problem:
I have a Python file with an import of
```
from math import sin,cos,sqrt
```
I need this file to still be 100% CPython compatible to allow my developers to write 100% CPython code and employ the great tools developed for Python.
Now enter Cython. In my Python file, the trig functions get called millions of times (fundamental to the code, can't change this). Is there any way that through some Python-fu in the main python file, or Cython magic otherwise I can instead use the C/C++ math functions using some variation on the Cython code
```
cdef extern from "math.h":
double sin(double)
```
That would give me near-C performance, which would be awesome.
[Stefan's talk](http://www.behnel.de/cython200910/talk.html) says specifically this can't be done, but the talk is two years old, and there are many creative people out there | 2012/04/27 | [
"https://Stackoverflow.com/questions/10350765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360263/"
] | In an [example](http://docs.cython.org/src/tutorial/external.html) from Cython's documentation, they use a cimport from a C library to achieve this:
```
from libc.math cimport sin
``` | I may have misunderstood your problem, but the [Cython documentation on interfacing with external C code](http://docs.cython.org/src/userguide/external_C_code.html#resolving-naming-conflicts-c-name-specifications) seems to suggest the following syntax:
```
cdef extern from "math.h":
double c_sin "sin" (double)
```
which gives the function the name `sin` in the C code (so that it correctly links to the function from `math.h`), and `c_sin` in the Python module. I'm not really sure I understand what this achieves in this case, though - why would you want to use `math.sin` in Cython code? Do you have some statically typed variables, and some dynamically typed ones? |
10,350,765 | Here is my basic problem:
I have a Python file with an import of
```
from math import sin,cos,sqrt
```
I need this file to still be 100% CPython compatible to allow my developers to write 100% CPython code and employ the great tools developed for Python.
Now enter Cython. In my Python file, the trig functions get called millions of times (fundamental to the code, can't change this). Is there any way that through some Python-fu in the main python file, or Cython magic otherwise I can instead use the C/C++ math functions using some variation on the Cython code
```
cdef extern from "math.h":
double sin(double)
```
That would give me near-C performance, which would be awesome.
[Stefan's talk](http://www.behnel.de/cython200910/talk.html) says specifically this can't be done, but the talk is two years old, and there are many creative people out there | 2012/04/27 | [
"https://Stackoverflow.com/questions/10350765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360263/"
] | Answering this question eight years later, this is what worked for me on Ubuntu 19.10 using the system CPython vesion 3.7.5 and Cython3 version 0.29.10 from the Ubuntu repostory.
The Cython documents on [Pure Python Mode](https://cython.readthedocs.io/en/latest/src/tutorial/pure.html) give an example that works. It looks a bit different to the examples in the old answers here so I guess the document has been updated since.
The Python file needs a *conditional* import, which works fine using normal CPython:
```none
#!/usr/bin/env python3
# from: https://cython.readthedocs.io/en/latest/src/tutorial/pure.html
# mymodule.py
import cython
# override with Python import if not in compiled code
if not cython.compiled:
from math import sin
# calls sin() from math.h when compiled with Cython and math.sin() in Python
print(sin(0.5))
```
The Cython language constructs must be put in a file with the same name but a ".pxd" suffix:
```none
#cython: language_level=3
# from: https://cython.readthedocs.io/en/latest/src/tutorial/pure.html
# mymodule.pxd
# declare a C function as "cpdef" to export it to the module
cdef extern from "math.h":
cpdef double sin(double x)
```
I used the "--embed" option to create C-code for a stand-alone Linux ELF executable to test this. The GCC compiler line needs "-lm" to import the maths module that contains sin.
```none
cython3 --embed mymodule.py
gcc -o mymodule mymodule.c -I/usr/include/python3.7 -lpython3.7m -lm
``` | I may have misunderstood your problem, but the [Cython documentation on interfacing with external C code](http://docs.cython.org/src/userguide/external_C_code.html#resolving-naming-conflicts-c-name-specifications) seems to suggest the following syntax:
```
cdef extern from "math.h":
double c_sin "sin" (double)
```
which gives the function the name `sin` in the C code (so that it correctly links to the function from `math.h`), and `c_sin` in the Python module. I'm not really sure I understand what this achieves in this case, though - why would you want to use `math.sin` in Cython code? Do you have some statically typed variables, and some dynamically typed ones? |
10,350,765 | Here is my basic problem:
I have a Python file with an import of
```
from math import sin,cos,sqrt
```
I need this file to still be 100% CPython compatible to allow my developers to write 100% CPython code and employ the great tools developed for Python.
Now enter Cython. In my Python file, the trig functions get called millions of times (fundamental to the code, can't change this). Is there any way that through some Python-fu in the main python file, or Cython magic otherwise I can instead use the C/C++ math functions using some variation on the Cython code
```
cdef extern from "math.h":
double sin(double)
```
That would give me near-C performance, which would be awesome.
[Stefan's talk](http://www.behnel.de/cython200910/talk.html) says specifically this can't be done, but the talk is two years old, and there are many creative people out there | 2012/04/27 | [
"https://Stackoverflow.com/questions/10350765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360263/"
] | In an [example](http://docs.cython.org/src/tutorial/external.html) from Cython's documentation, they use a cimport from a C library to achieve this:
```
from libc.math cimport sin
``` | Answering this question eight years later, this is what worked for me on Ubuntu 19.10 using the system CPython vesion 3.7.5 and Cython3 version 0.29.10 from the Ubuntu repostory.
The Cython documents on [Pure Python Mode](https://cython.readthedocs.io/en/latest/src/tutorial/pure.html) give an example that works. It looks a bit different to the examples in the old answers here so I guess the document has been updated since.
The Python file needs a *conditional* import, which works fine using normal CPython:
```none
#!/usr/bin/env python3
# from: https://cython.readthedocs.io/en/latest/src/tutorial/pure.html
# mymodule.py
import cython
# override with Python import if not in compiled code
if not cython.compiled:
from math import sin
# calls sin() from math.h when compiled with Cython and math.sin() in Python
print(sin(0.5))
```
The Cython language constructs must be put in a file with the same name but a ".pxd" suffix:
```none
#cython: language_level=3
# from: https://cython.readthedocs.io/en/latest/src/tutorial/pure.html
# mymodule.pxd
# declare a C function as "cpdef" to export it to the module
cdef extern from "math.h":
cpdef double sin(double x)
```
I used the "--embed" option to create C-code for a stand-alone Linux ELF executable to test this. The GCC compiler line needs "-lm" to import the maths module that contains sin.
```none
cython3 --embed mymodule.py
gcc -o mymodule mymodule.c -I/usr/include/python3.7 -lpython3.7m -lm
``` |
2,844,365 | im a novice into developing an application using backend as Python (2.5) and Qt(3) as front end GUI designer. I have 5 diffrent dialogs to implement the scripts. i just know to load the window (main window)
```
from qt import *
from dialogselectkernelfile import *
from formcopyextract import *
import sys
if __name__ == "__main__":
app = QApplication(sys.argv)
f = DialogSelectKernelFile()
f.show()
app.setMainWidget(f)
app.exec_loop()
```
main dialog opens on running. i have a set of back,Next,Cancel buttons pusing on each should open the next or previous dialogs. i use the pyuic compiler to source translation.how can i do this from python. please reply i`m running out of time.i dont know how to load another dialog from a signal of push button in another dialog. Help me pls
Thanks a Lot | 2010/05/16 | [
"https://Stackoverflow.com/questions/2844365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/995052/"
] | As Ryan Bigg suggested `simple_format` is the best tool for the job: it's 'l safe' and much neater than other solutions.
so for @var:
```
<%= simple_format(@var) %>
```
If you need to sanitize the text to get rid of HTML tags, you should do this *before* passing it to `simple_format`
<http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format> | The best way I can figure to go about this is using the sanitize method to strip all but the BR tag we want.
Assume that we have `@var` with the content `"some\ntext"`:
Trying `<%= @var.gsub(/\n/, '<br />') %>` doesn't work.
Trying `<%= h @var.gsub(/\n/, '<br />').html_safe %>` doesn't work and is unsafe.
Trying `<%= sanitize(@var.gsub(/\n/, '<br />'), :tags => %w(br) %>` WORKS.
I haven't tested this very well, but it allows the BR tag to work, and replaced a dummy script alert I added with white space, so it seems to be doing its job. If anyone else has an idea or can say if this is a safe solution, please do.
Update:
Another idea suggested by Jose Valim:
`<%= h(@var).gsub(/\n/, '<br />') %>` Works |
2,844,365 | im a novice into developing an application using backend as Python (2.5) and Qt(3) as front end GUI designer. I have 5 diffrent dialogs to implement the scripts. i just know to load the window (main window)
```
from qt import *
from dialogselectkernelfile import *
from formcopyextract import *
import sys
if __name__ == "__main__":
app = QApplication(sys.argv)
f = DialogSelectKernelFile()
f.show()
app.setMainWidget(f)
app.exec_loop()
```
main dialog opens on running. i have a set of back,Next,Cancel buttons pusing on each should open the next or previous dialogs. i use the pyuic compiler to source translation.how can i do this from python. please reply i`m running out of time.i dont know how to load another dialog from a signal of push button in another dialog. Help me pls
Thanks a Lot | 2010/05/16 | [
"https://Stackoverflow.com/questions/2844365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/995052/"
] | The best way I can figure to go about this is using the sanitize method to strip all but the BR tag we want.
Assume that we have `@var` with the content `"some\ntext"`:
Trying `<%= @var.gsub(/\n/, '<br />') %>` doesn't work.
Trying `<%= h @var.gsub(/\n/, '<br />').html_safe %>` doesn't work and is unsafe.
Trying `<%= sanitize(@var.gsub(/\n/, '<br />'), :tags => %w(br) %>` WORKS.
I haven't tested this very well, but it allows the BR tag to work, and replaced a dummy script alert I added with white space, so it seems to be doing its job. If anyone else has an idea or can say if this is a safe solution, please do.
Update:
Another idea suggested by Jose Valim:
`<%= h(@var).gsub(/\n/, '<br />') %>` Works | Here's [what I did](https://stackoverflow.com/a/29669181/52499):
```
module ApplicationHelper
def nl2br s
sanitize(s, tags: []).gsub(/\n/, '<br>').html_safe
end
end
``` |
2,844,365 | im a novice into developing an application using backend as Python (2.5) and Qt(3) as front end GUI designer. I have 5 diffrent dialogs to implement the scripts. i just know to load the window (main window)
```
from qt import *
from dialogselectkernelfile import *
from formcopyextract import *
import sys
if __name__ == "__main__":
app = QApplication(sys.argv)
f = DialogSelectKernelFile()
f.show()
app.setMainWidget(f)
app.exec_loop()
```
main dialog opens on running. i have a set of back,Next,Cancel buttons pusing on each should open the next or previous dialogs. i use the pyuic compiler to source translation.how can i do this from python. please reply i`m running out of time.i dont know how to load another dialog from a signal of push button in another dialog. Help me pls
Thanks a Lot | 2010/05/16 | [
"https://Stackoverflow.com/questions/2844365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/995052/"
] | As Ryan Bigg suggested `simple_format` is the best tool for the job: it's 'l safe' and much neater than other solutions.
so for @var:
```
<%= simple_format(@var) %>
```
If you need to sanitize the text to get rid of HTML tags, you should do this *before* passing it to `simple_format`
<http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format> | Here's [what I did](https://stackoverflow.com/a/29669181/52499):
```
module ApplicationHelper
def nl2br s
sanitize(s, tags: []).gsub(/\n/, '<br>').html_safe
end
end
``` |
56,674,550 | I want to split a text that contains numbers
```
text = "bla bla 1 bla bla bla 142 bla bla (234.22)"
```
and want to add a `'\n'` before and after each number.
```
> "bla bla \n1\n bla bla bla \n142\n bla bla (234.22)"
```
The following function gives me the sub strings, but it throws away the pattern, i.e. the numbers. What is the best way to replace a pattern with something that contains the pattern in python?
```
re.split(' [0123456789]+ ', text)
``` | 2019/06/19 | [
"https://Stackoverflow.com/questions/56674550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5452008/"
] | Use
```
s = re.sub(r' \d+ ', '\n\\g<0>\n', s)
```
See the [regex demo](https://regex101.com/r/081OkV/1).
To replace only standalone numbers as whole words use
```
s = re.sub(r'\b\d+\b', '\n\\g<0>\n', s)
```
If you want to match the numbers enclosed with whitespaces only use either of
```
re.sub(r'(?<!\S)\d+(?!\S)', '\n\\g<0>\n', s) # also at the start/end of string
re.sub(r'(?<=\s)\d+(?=\s)', '\n\\g<0>\n', s) # only between whitespaces
```
Actually, the replacement can be specified as `'\n\g<0>\n'`, as `\g` is an undefined escape sequence and the backslash will be treated as literal char in this case and will be preserved in the resulting string to form the regex backreference construct.
[Python demo](https://ideone.com/KAhtZj):
```
import re
s = "bla bla 1 bla bla bla 142 bla bla"
s = re.sub(r'\b\d+\b', '\n\\g<0>\n', s)
print(s) # => bla bla \n1\n bla bla bla \n142\n bla bla
``` | Try this code!! This might help!
```
import re
text = "bla bla 1 bla bla bla 142 bla bla"
replaced = re.sub('([0-9]+)', r'\n\1\n',text)
print(replaced)
Output: 'bla bla \n1\n bla bla bla \n142\n bla bla'
``` |
63,610,350 | I have int in python that I want to reverse
`x = int(1234567899)`
I want to result will be `3674379849`
explain : = `1234567899` = `0x499602DB` and `3674379849` = `0xDB029649`
How to do that in python ? | 2020/08/27 | [
"https://Stackoverflow.com/questions/63610350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13767076/"
] | ```
>>> import struct
>>> struct.unpack('>I', struct.pack('<I', 1234567899))[0]
3674379849
>>>
```
This converts the integer to a 4-byte array (`I`), then decodes it in reverse order (`>` vs `<`).
Documentation: [`struct`](https://docs.python.org/3/library/struct.html) | If you just want the result, use [sabiks approach](https://stackoverflow.com/a/63610471/7505395) - if you want the intermediate steps for bragging rights, you would need to
* create the hex of the number (#1) and maybe add a leading 0 for correctness
* reverse it 2-byte-wise (#2)
* create an integer again (#3)
f.e. like so
```
n = 1234567899
# 1
h = hex(n)
if len(h) % 2: # fix for uneven lengthy inputs (f.e. n = int("234",16))
h = '0x0'+h[2:]
# 2 (skips 0x and prepends 0x for looks only)
bh = '0x'+''.join([h[i: i+2] for i in range(2, len(h), 2)][::-1])
# 3
b = int(bh, 16)
print(n, h, bh, b)
```
to get
```
1234567899 0x499602db 0xdb029649 3674379849
``` |
71,632,619 | I am new to Python. I have a XML file("topstocks.xml") with some elements and attributes which looks like as below. I was trying to pass an attribute "id" as a function parameter, so that I can dynamically fetch the data.
```
<properties>
<property id="H01" cost="106000" state="NM" percentage="0.12">2925.6</property>
<property id="H02" cost="125000" state="AZ" percentage="0.15">4500</property>
<property id="H03" cost="119000" state="NH" percentage="0.13">3248.7</property>
</properties>
```
My python code goes like this.
```
import xml.etree.cElementTree as ET
tree = ET.parse("topstocks.xml")
root = tree.getroot()
def find_all(id ='H02'): # I am trying to pass attribute "id"
stocks = []
for child in root.iter("property"):
data = child.attrib.copy()
data["cost"] = float(data["cost"])
data["percentage"] = float(data["percentage"])
data["netIncome"] = float(child.text)
stocks.append(data)
return stocks
def FindAll(id ='H02'):
settings = find_all(id)
return settings
if __name__=="__main__":
idSelection = "H02"
result= FindAll(id=idSelection)
print(result)
```
It's output should print.
{'id': 'H02', 'cost': 125000.0,'state': 'AZ', 'percentage': 0.15, 'netIncome': 4500.0}
Thank you in advance. | 2022/03/26 | [
"https://Stackoverflow.com/questions/71632619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14810351/"
] | You cannot combine make constructs, like `ifeq`, with shell constructs, like setting a shell variable. Makefiles are not scripts, like a shell script or a python script or whatever.
Make works in two distinct phases: first ALL the makefiles are parsed, all make variables are assigned, all `ifeq` statements are resolved, and all targets and prerequisites are parsed and make constructs an internal graph of all the relationships between them. Basically, everything that is not indented with a TAB is parsed in this phase.
Second, after ALL makefiles are parsed, make will walk (some part of) the graph created in the first step and, for targets that are out of date, it will expand the recipe (which is a shell script) then run a shell and give it the recipe. Everything that's indented with a TAB is handled in this phase.
So, clearly you can't have ifeq conditions (expanded during the first phase) that depend on actions in recipes (run in the second phase).
You can write your makefile like this:
```
VALUE_TO_TEST = bad_value
MISMATCH =
ifeq ($(VALUE_TO_TEST), expected_value)
MISMATCH = yes
endif
all:
ifdef MISMATCH
# Do thing because there is a mismatch
else
# Do thing where there is no mismatch
endif
```
I expect you don't want to do this, but although this second example is better than the first it still doesn't really explain enough about what you want to do, and why it's not acceptable to do things this way. | Sigh - so the answer after MANY permutations is the tab mistake:
```
a =
MISMATCH=
all:
ifeq ($(a),)
MISMATCH=yes
endif
ifdef MISMATCH
$(info fooz)
else
$(info bark)
endif
```
(make files are so frustrating) |
66,109,204 | I have a file called `setup.sh` which basically has this
```
python3 -m venv env
source ./env/bin/activate
# other setup stuff
```
When I run `sh setup.sh`, the environment folder `env` is created, and it will run my `#other setup stuff`, but it will skip over `source ./env/bin/activate`, which puts me in my environment.
The command runs just fine if I do so in the terminal(I have a macbook), but not in my bash file.
Three ideas I've tried:
1. ensuring execute priviges: `chmod +x setup.sh`
2. change the line `source ./env/bin/activate` to `. ./env/bin/activate`
3. run the file using `bash setup.sh` instead of `sh setup.sh`
Is there a smarter way to go about being put in my environment, or some way I can get the `source` to run? | 2021/02/08 | [
"https://Stackoverflow.com/questions/66109204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14745324/"
] | ### global variable and change listener
You can add an event listener listening for changes for the checkbox.
You can use a global variable which gets track of the unchecked boxes.
```
let countUnchecked = 0;
```
Initially its *value is 0* when you add a new checkbox its value *increases by one*. When the box gets selected it increases by one and when it gets deselected it decreases by one.
```
itemCheck.addEventListener('change', function() {
if (itemCheck.checked) {
countUnchecked--;
document.getElementById('unchecked-count').innerText = countUnchecked;
} else {
counter++;
document.getElementById('unchecked-count').innerText = countUnchecked;
}
```
```js
let todos = []
let countUnchecked = 0;
function reflectToHTML(i) {
let count = todos.length
let listItem = document.createElement('li'),
itemCheck = document.createElement('input')
itemCheck.type = 'checkbox'
itemCheck.id = 'check' + todos.length
listItem.append(itemCheck, i['text'])
itemCheck.addEventListener('change', function() {
if (itemCheck.checked) {
countUnchecked--;
document.getElementById('unchecked-count').innerText = countUnchecked;
} else {
countUnchecked++;
document.getElementById('unchecked-count').innerText = countUnchecked;
}
})
document.getElementById('todo-list').appendChild(listItem)
document.getElementById('item-count').innerText = todos.length
countUnchecked++;
document.getElementById('unchecked-count').innerText = countUnchecked;
}
function createTodo() {
let newTodo = {
text: '',
checked: 0
}
newTodo['text'] = prompt('Item description')
if (newTodo['text'] != null) {
todos.push(newTodo)
reflectToHTML(newTodo)
}
}
```
```html
<div class="container center">
<h1 class="center title">My TODO App</h1>
<div class="flow-right controls">
<span>Item count: <span id="item-count">0</span></span>
<span>Unchecked count: <span id="unchecked-count">0</span></span>
</div>
<button class="button center" onClick="createTodo();">New TODO</button>
<ul id="todo-list" class="todo-list">
</ul>
</div>
``` | You can add an event listener just for the `<ul>` element and not for each `type='checkbox'` element ex:
```js
document.querySelector("#todo-list").onchange = function() {
document.querySelector("#unchecked-count").textContent = this.querySelectorAll("[type=checkbox]:not(:checked)").length;
}
```
so here on each change we get the node list of the unchecked checkbox elements of that ul element and set the counter the length of that list. |
22,146,205 | ### Context:
I have been playing around with python's wrapper for opencv2.
I wanted to play with a few ideas and use a wide angle camera similar to 'rear view' cameras in cars.
I got one from a scrapped crash car (its got 4 wires) I took an educated guess from the wires color codding, connect it up so that I power the power and ground line from a usb type A and feed the NTSC composite+ composite- from an RCA connector.
I bought a NTSC to usb converter [like this one](http://www.ebay.com/itm/like/231153493687?lpid=97).
It came with drivers and some off the shelf VHStoDVD software.
### the problem:
I used the run of the mill examples online to trial test it like this:
```
import numpy as np
import cv2
cam_index=0
cap=cv2.VideoCapture(cam_index)
print cap.isOpened()
ret, frame=cap.read()
#print frame.shape[0]
#print frame.shape[1]
while (cap.isOpened()):
ret, frame=cap.read()
#gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#release and close
cap.release()
cv2.destroyAllWindows()
```
this is the output from shell:
```
True
Traceback (most recent call last):
File "C:/../cam_capture_.py", line 19, in <module>
cv2.imshow('frame', frame)
error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow
>>>
```
### key Observations:
[SCREENSHOTS](http://imgur.com/a/gXqr3#1)
1. in control panel the usb dongle is shown as 'OEM capture' in Sound Video & Game controllers . So it's not seen as a simple plug and play Webcam in 'Imaging devices'
2. If I open the VHStoDVD software I need to configure 2 aspects:
* set as Composite
* set enconding as NTSC
then the camera feed from the analog camera is shown OK within the VHStoDVD application
3. When I open the device video channel in FLV (device capture). The device stream is just a black screen but IF i open the VHStoDVD software WHILE flv is streaming I get the camera's feed to stream on FLV and a black screen is shown on the VHStoDVD feed. Another important difference is that there is huge latency of aprox 0.5sec when the feed is in FLV as opposed to running in VHStoDVD.
4. When running "cam\_capture.py" as per the sample code above at some put during runtime i will eventually get a stop error code 0x0000008e:
detail:
```
stop: 0x0000008E (0xC0000005, 0xB8B5F417, 0X9DC979F4, 0X00000000 )
ks.sys - Address B8B5F417 base at B8B5900, Datestamp...
beg mem dump
phy mem dump complete
```
5.if i try to print frame.shape[0] or frame.shape[1] I get a type error say I cannot print type None
6.if try other cam\_index the result is always false
### TLDR:
In 'control panel' the camera device is under 'sound video & game controllers' not under 'imaging devices';
The cam\_index==zero;
The capture.isOpened()=True;
The frame size is None;
If VHStoDVD is running with composite NTSC configured the camera works , obviously you cant see the image with printscreen in attachment but trust me ! ;)
Is there any form of initialisation of the start of communication with the dongle that could fix this i.e. emulate VHStoDVD settings (composite+NTSC)? I thought I could buspirate the start of comms between VHStoDVD and the dongle but it feels like I am going above and beyond to do something I thought was a key turn solution.
Any constructive insights, suggestion , corrections are most welcome!
Thanks
Cheers | 2014/03/03 | [
"https://Stackoverflow.com/questions/22146205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3380927/"
] | Ok , so after deeper investigation the initial suspicion was confirmed i.e. because the NTSC dongle is not handled as an imaging device (it's seen as a Video Controller , so similar to an emulation of a TV Tuner card ) it means that although we are able to call cv2.VideoCapture with cam\_index=0 the video channel itself is not transmitting because we are required to define a bunch of parameters
1. encoding
2. frame size
3. fps rate etc
The problem is because the device is not supported as an imaging device calling cv2.VideoCapture.set(parameter, value) doesn't seem to change anything on the original video feed.
I didn't find a solution but I found a work around. There seems to be quite a few options online. Search for keywords DV to webcam or camcorder as a webcam.
I used DVdriver (<http://www.trackerpod.com/TCamWeb/download.htm>) (i used the trial because I am cheap!).
Why does it work?
-----------------
As much as I can tell DVdriver receives the data from the device which is set as a Video controller (similar to a capture from "Windows Movie Maker" or ffmpeg) and then through "fairydust" outputs the frames on cam\_index=0 (assumed no other cam connected) as an 'imaging device' webcam.
Summary
-------
TLDR use DVdriver or similar.
I found a workaround but I would really like to understand it from first principles and possible generate a similar initialisation of the NTSC dongle from within python, without any other software dependencies but until then, hopefully this will help others who were also struggling or assuming it was a hardware issue.
I will now leave you with some Beckett:
Ever tried. Ever failed. No matter. Try again. Fail again. Fail better. (!) | It's a few months late, but might be useful. I was working on a Windows computer and had installed the drivers that came with the device, I tried the same code as your question with an Ezcap from Somagic and got the same error. Since "frame is None," I decided to try an if statement around it - in case it was an initialization error. Placing into the loop:
```
if frame is None:
print 0
else:
print 1
```
The result is: 01110111111111111111111111111...
And if the frame = cap.read(), above the loop is commented out - I get: 00111111111111111...
So for my device capture device it appears to be working for all frames beyond the 5th are captured. I'm not sure why this is, but it might be a useful work around for now.
*Disclaimer: Unfortunately, my camera input is currently in a radiation field so I can't get to it for a couple of weeks to make sure it works for sure. However, the images are currently a black frame (which is expected without proper input).* |
22,146,205 | ### Context:
I have been playing around with python's wrapper for opencv2.
I wanted to play with a few ideas and use a wide angle camera similar to 'rear view' cameras in cars.
I got one from a scrapped crash car (its got 4 wires) I took an educated guess from the wires color codding, connect it up so that I power the power and ground line from a usb type A and feed the NTSC composite+ composite- from an RCA connector.
I bought a NTSC to usb converter [like this one](http://www.ebay.com/itm/like/231153493687?lpid=97).
It came with drivers and some off the shelf VHStoDVD software.
### the problem:
I used the run of the mill examples online to trial test it like this:
```
import numpy as np
import cv2
cam_index=0
cap=cv2.VideoCapture(cam_index)
print cap.isOpened()
ret, frame=cap.read()
#print frame.shape[0]
#print frame.shape[1]
while (cap.isOpened()):
ret, frame=cap.read()
#gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#release and close
cap.release()
cv2.destroyAllWindows()
```
this is the output from shell:
```
True
Traceback (most recent call last):
File "C:/../cam_capture_.py", line 19, in <module>
cv2.imshow('frame', frame)
error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow
>>>
```
### key Observations:
[SCREENSHOTS](http://imgur.com/a/gXqr3#1)
1. in control panel the usb dongle is shown as 'OEM capture' in Sound Video & Game controllers . So it's not seen as a simple plug and play Webcam in 'Imaging devices'
2. If I open the VHStoDVD software I need to configure 2 aspects:
* set as Composite
* set enconding as NTSC
then the camera feed from the analog camera is shown OK within the VHStoDVD application
3. When I open the device video channel in FLV (device capture). The device stream is just a black screen but IF i open the VHStoDVD software WHILE flv is streaming I get the camera's feed to stream on FLV and a black screen is shown on the VHStoDVD feed. Another important difference is that there is huge latency of aprox 0.5sec when the feed is in FLV as opposed to running in VHStoDVD.
4. When running "cam\_capture.py" as per the sample code above at some put during runtime i will eventually get a stop error code 0x0000008e:
detail:
```
stop: 0x0000008E (0xC0000005, 0xB8B5F417, 0X9DC979F4, 0X00000000 )
ks.sys - Address B8B5F417 base at B8B5900, Datestamp...
beg mem dump
phy mem dump complete
```
5.if i try to print frame.shape[0] or frame.shape[1] I get a type error say I cannot print type None
6.if try other cam\_index the result is always false
### TLDR:
In 'control panel' the camera device is under 'sound video & game controllers' not under 'imaging devices';
The cam\_index==zero;
The capture.isOpened()=True;
The frame size is None;
If VHStoDVD is running with composite NTSC configured the camera works , obviously you cant see the image with printscreen in attachment but trust me ! ;)
Is there any form of initialisation of the start of communication with the dongle that could fix this i.e. emulate VHStoDVD settings (composite+NTSC)? I thought I could buspirate the start of comms between VHStoDVD and the dongle but it feels like I am going above and beyond to do something I thought was a key turn solution.
Any constructive insights, suggestion , corrections are most welcome!
Thanks
Cheers | 2014/03/03 | [
"https://Stackoverflow.com/questions/22146205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3380927/"
] | Ok , so after deeper investigation the initial suspicion was confirmed i.e. because the NTSC dongle is not handled as an imaging device (it's seen as a Video Controller , so similar to an emulation of a TV Tuner card ) it means that although we are able to call cv2.VideoCapture with cam\_index=0 the video channel itself is not transmitting because we are required to define a bunch of parameters
1. encoding
2. frame size
3. fps rate etc
The problem is because the device is not supported as an imaging device calling cv2.VideoCapture.set(parameter, value) doesn't seem to change anything on the original video feed.
I didn't find a solution but I found a work around. There seems to be quite a few options online. Search for keywords DV to webcam or camcorder as a webcam.
I used DVdriver (<http://www.trackerpod.com/TCamWeb/download.htm>) (i used the trial because I am cheap!).
Why does it work?
-----------------
As much as I can tell DVdriver receives the data from the device which is set as a Video controller (similar to a capture from "Windows Movie Maker" or ffmpeg) and then through "fairydust" outputs the frames on cam\_index=0 (assumed no other cam connected) as an 'imaging device' webcam.
Summary
-------
TLDR use DVdriver or similar.
I found a workaround but I would really like to understand it from first principles and possible generate a similar initialisation of the NTSC dongle from within python, without any other software dependencies but until then, hopefully this will help others who were also struggling or assuming it was a hardware issue.
I will now leave you with some Beckett:
Ever tried. Ever failed. No matter. Try again. Fail again. Fail better. (!) | I faced the same issue. As a workaround, I first tried the solution proposed by @user3380927 and it worked indeed. But since I didn't want to rely on an external software, I started tweaking parameters using opencv in Python.
This lines of code worked like a charm (you have to insert them before reading the frame for the first time):
```
cam.set(cv2.CAP_FFMPEG,True)
cam.set(cv2.CAP_PROP_FPS,30)
```
So, the full code for basic camera reading is as follows:
```
import cv2
cam = cv2.VideoCapture(1)
cam.set(cv2.CAP_FFMPEG,True)
cam.set(cv2.CAP_PROP_FPS,30)
while(True):
ret,frame = cam.read()
cv2.imshow('frame',frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
cam.release()
cv2.destroyAllWindows()
```
You can then apply image processing operations as usual. Just for reference, this was my configuration:
* Opencv 3.1.0
* Python 2.7.5
* Windows 8.1
* Elgato Video Capture device (this was also shown as Sound Video & Game controllers) |
22,146,205 | ### Context:
I have been playing around with python's wrapper for opencv2.
I wanted to play with a few ideas and use a wide angle camera similar to 'rear view' cameras in cars.
I got one from a scrapped crash car (its got 4 wires) I took an educated guess from the wires color codding, connect it up so that I power the power and ground line from a usb type A and feed the NTSC composite+ composite- from an RCA connector.
I bought a NTSC to usb converter [like this one](http://www.ebay.com/itm/like/231153493687?lpid=97).
It came with drivers and some off the shelf VHStoDVD software.
### the problem:
I used the run of the mill examples online to trial test it like this:
```
import numpy as np
import cv2
cam_index=0
cap=cv2.VideoCapture(cam_index)
print cap.isOpened()
ret, frame=cap.read()
#print frame.shape[0]
#print frame.shape[1]
while (cap.isOpened()):
ret, frame=cap.read()
#gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#release and close
cap.release()
cv2.destroyAllWindows()
```
this is the output from shell:
```
True
Traceback (most recent call last):
File "C:/../cam_capture_.py", line 19, in <module>
cv2.imshow('frame', frame)
error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow
>>>
```
### key Observations:
[SCREENSHOTS](http://imgur.com/a/gXqr3#1)
1. in control panel the usb dongle is shown as 'OEM capture' in Sound Video & Game controllers . So it's not seen as a simple plug and play Webcam in 'Imaging devices'
2. If I open the VHStoDVD software I need to configure 2 aspects:
* set as Composite
* set enconding as NTSC
then the camera feed from the analog camera is shown OK within the VHStoDVD application
3. When I open the device video channel in FLV (device capture). The device stream is just a black screen but IF i open the VHStoDVD software WHILE flv is streaming I get the camera's feed to stream on FLV and a black screen is shown on the VHStoDVD feed. Another important difference is that there is huge latency of aprox 0.5sec when the feed is in FLV as opposed to running in VHStoDVD.
4. When running "cam\_capture.py" as per the sample code above at some put during runtime i will eventually get a stop error code 0x0000008e:
detail:
```
stop: 0x0000008E (0xC0000005, 0xB8B5F417, 0X9DC979F4, 0X00000000 )
ks.sys - Address B8B5F417 base at B8B5900, Datestamp...
beg mem dump
phy mem dump complete
```
5.if i try to print frame.shape[0] or frame.shape[1] I get a type error say I cannot print type None
6.if try other cam\_index the result is always false
### TLDR:
In 'control panel' the camera device is under 'sound video & game controllers' not under 'imaging devices';
The cam\_index==zero;
The capture.isOpened()=True;
The frame size is None;
If VHStoDVD is running with composite NTSC configured the camera works , obviously you cant see the image with printscreen in attachment but trust me ! ;)
Is there any form of initialisation of the start of communication with the dongle that could fix this i.e. emulate VHStoDVD settings (composite+NTSC)? I thought I could buspirate the start of comms between VHStoDVD and the dongle but it feels like I am going above and beyond to do something I thought was a key turn solution.
Any constructive insights, suggestion , corrections are most welcome!
Thanks
Cheers | 2014/03/03 | [
"https://Stackoverflow.com/questions/22146205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3380927/"
] | It's a few months late, but might be useful. I was working on a Windows computer and had installed the drivers that came with the device, I tried the same code as your question with an Ezcap from Somagic and got the same error. Since "frame is None," I decided to try an if statement around it - in case it was an initialization error. Placing into the loop:
```
if frame is None:
print 0
else:
print 1
```
The result is: 01110111111111111111111111111...
And if the frame = cap.read(), above the loop is commented out - I get: 00111111111111111...
So for my device capture device it appears to be working for all frames beyond the 5th are captured. I'm not sure why this is, but it might be a useful work around for now.
*Disclaimer: Unfortunately, my camera input is currently in a radiation field so I can't get to it for a couple of weeks to make sure it works for sure. However, the images are currently a black frame (which is expected without proper input).* | I faced the same issue. As a workaround, I first tried the solution proposed by @user3380927 and it worked indeed. But since I didn't want to rely on an external software, I started tweaking parameters using opencv in Python.
This lines of code worked like a charm (you have to insert them before reading the frame for the first time):
```
cam.set(cv2.CAP_FFMPEG,True)
cam.set(cv2.CAP_PROP_FPS,30)
```
So, the full code for basic camera reading is as follows:
```
import cv2
cam = cv2.VideoCapture(1)
cam.set(cv2.CAP_FFMPEG,True)
cam.set(cv2.CAP_PROP_FPS,30)
while(True):
ret,frame = cam.read()
cv2.imshow('frame',frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
cam.release()
cv2.destroyAllWindows()
```
You can then apply image processing operations as usual. Just for reference, this was my configuration:
* Opencv 3.1.0
* Python 2.7.5
* Windows 8.1
* Elgato Video Capture device (this was also shown as Sound Video & Game controllers) |
10,002,937 | I have some pom files in my project with the following structure
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>xparent</artifactId>
<groupId>y</groupId>
<version>2.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>someparent</artifactId>
<version>x.x.x-needs_change</version>
<packaging>pom</packaging>
<name>some name</name>
<description>some description</description>
<url>myurl</url>
<modules>
<module>mymodules</module>
</modules>
<properties>
<my.version>x.x.x-needs_change</my.version>
</properties>
<dependencies>
<dependency>
<groupId>hhhhh</groupId>
<artifactId>hhhhh</artifactId>
<version>x.x.x-should not change</version>
</dependency>
</dependencies>
</project>
```
I am using sed to give the current version as input and change it to a new version given. But I do not want to change version within dependency block. How do I do this?
I do not want to go the maven version plugin route. I have tried it and it does not suit my requirements.
I prefer sed / python script.
Thanks | 2012/04/03 | [
"https://Stackoverflow.com/questions/10002937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164061/"
] | You could try:
```
sed -e '/<dependencies>/,/<\/dependencies>/ !{
s!<version>[0-9.]\+</version>!<version>'"$NEWVERSION"'</version>!
}' MY_FILE
```
The `/<dependencies>/,/<\/dependencies>/` says "find all lines between `<dependencies>` and `</dependencies>`".
The `!` after that says "perform the following actions everywhere **but** those lines (i.e. do this for all lines *except* between `<dependencies>` and `</dependencies>`)".
The `s!<version>[0-9.]\+</version>!<version>'"$NEWVERSION"'</version>!` says "replace `<version>...</version>` with `<version>$NEWVERSION</version>`, where `$NEWVERSION` is some environment variable that contains the new version number.
The farting around with the quotes (`'"$NEWVERSION"'`) was because I wanted single quotes for the main part of the sed command (so I don't have to worry about the exclamation mark & backslashes), but I *do* want `$NEWVERSION` to be expanded.
Modify to suit your script. | ```
nawk '{
a=$0;
getline;
if($0!~/depend/ && a!~/version/)
{gsub(/2.0.0/,"1.0.0",$0);print a"\n"$0}
else print a"\n"$0
}' file3
```
Below is the test:
```
pearl.302> cat file3
<parent>
<aritifactID> </artifactID>
<groupID> </groupID>
<version>2.0.0</version>
</parent>
<properties>
<version>2.0.0</version>
</properties>
<dependencies>
<dependency>
<version>2.0.0</version>
</dependency>
</dependencies>
pearl.303> nawk '{a=$0;
getline;
if($0!~/depend/ && a!~/version/)
{gsub(/2.0.0/,"1.0.0",$0);print a"\n"$0}
else print a"\n"$0 }' file3
<parent>
<aritifactID> </artifactID>
<groupID> </groupID>
<version>1.0.0</version>
</parent>
<properties>
<version>1.0.0</version>
</properties>
<dependencies>
<dependency>
<version>2.0.0</version>
</dependency>
</dependencies>
``` |
10,002,937 | I have some pom files in my project with the following structure
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>xparent</artifactId>
<groupId>y</groupId>
<version>2.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>someparent</artifactId>
<version>x.x.x-needs_change</version>
<packaging>pom</packaging>
<name>some name</name>
<description>some description</description>
<url>myurl</url>
<modules>
<module>mymodules</module>
</modules>
<properties>
<my.version>x.x.x-needs_change</my.version>
</properties>
<dependencies>
<dependency>
<groupId>hhhhh</groupId>
<artifactId>hhhhh</artifactId>
<version>x.x.x-should not change</version>
</dependency>
</dependencies>
</project>
```
I am using sed to give the current version as input and change it to a new version given. But I do not want to change version within dependency block. How do I do this?
I do not want to go the maven version plugin route. I have tried it and it does not suit my requirements.
I prefer sed / python script.
Thanks | 2012/04/03 | [
"https://Stackoverflow.com/questions/10002937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164061/"
] | You could try:
```
sed -e '/<dependencies>/,/<\/dependencies>/ !{
s!<version>[0-9.]\+</version>!<version>'"$NEWVERSION"'</version>!
}' MY_FILE
```
The `/<dependencies>/,/<\/dependencies>/` says "find all lines between `<dependencies>` and `</dependencies>`".
The `!` after that says "perform the following actions everywhere **but** those lines (i.e. do this for all lines *except* between `<dependencies>` and `</dependencies>`)".
The `s!<version>[0-9.]\+</version>!<version>'"$NEWVERSION"'</version>!` says "replace `<version>...</version>` with `<version>$NEWVERSION</version>`, where `$NEWVERSION` is some environment variable that contains the new version number.
The farting around with the quotes (`'"$NEWVERSION"'`) was because I wanted single quotes for the main part of the sed command (so I don't have to worry about the exclamation mark & backslashes), but I *do* want `$NEWVERSION` to be expanded.
Modify to suit your script. | To parse and modify XML - you really should use a xml aware parser, such as [lxml](http://lxml.de/parsing.html) instead of text tools such as `sed` or `awk`
I assume that your POM files are indeed valid POM files, i.e. they have the enclosing `<project>` tag as well.
```
>>> t = """<project>
... <parent>
... <artifactID> </artifactID>
... <groupID> </groupID>
... <version>2.0.0</version>
... </parent>
...
... <properties>
... <version>2.0.0</version>
... </properties>
...
... <dependencies>
... <dependency>
... <version>2.0.0</version>
... </dependency>
... </dependencies></project>
... """
>>> from lxml import etree
>>> r = etree.fromstring(t)
>>> r.xpath("//parent/version")[0].text = "3.0"
>>> r.xpath("//properties/version")[0].text = "3.0"
>>> print(etree.tostring(r))
<project>
<parent>
<artifactID> </artifactID>
<groupID> </groupID>
<version>3.0</version>
</parent>
<properties>
<version>3.0</version>
</properties>
<dependencies>
<dependency>
<version>2.0.0</version>
</dependency>
</dependencies></project>
``` |
10,002,937 | I have some pom files in my project with the following structure
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>xparent</artifactId>
<groupId>y</groupId>
<version>2.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>someparent</artifactId>
<version>x.x.x-needs_change</version>
<packaging>pom</packaging>
<name>some name</name>
<description>some description</description>
<url>myurl</url>
<modules>
<module>mymodules</module>
</modules>
<properties>
<my.version>x.x.x-needs_change</my.version>
</properties>
<dependencies>
<dependency>
<groupId>hhhhh</groupId>
<artifactId>hhhhh</artifactId>
<version>x.x.x-should not change</version>
</dependency>
</dependencies>
</project>
```
I am using sed to give the current version as input and change it to a new version given. But I do not want to change version within dependency block. How do I do this?
I do not want to go the maven version plugin route. I have tried it and it does not suit my requirements.
I prefer sed / python script.
Thanks | 2012/04/03 | [
"https://Stackoverflow.com/questions/10002937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164061/"
] | You could try:
```
sed -e '/<dependencies>/,/<\/dependencies>/ !{
s!<version>[0-9.]\+</version>!<version>'"$NEWVERSION"'</version>!
}' MY_FILE
```
The `/<dependencies>/,/<\/dependencies>/` says "find all lines between `<dependencies>` and `</dependencies>`".
The `!` after that says "perform the following actions everywhere **but** those lines (i.e. do this for all lines *except* between `<dependencies>` and `</dependencies>`)".
The `s!<version>[0-9.]\+</version>!<version>'"$NEWVERSION"'</version>!` says "replace `<version>...</version>` with `<version>$NEWVERSION</version>`, where `$NEWVERSION` is some environment variable that contains the new version number.
The farting around with the quotes (`'"$NEWVERSION"'`) was because I wanted single quotes for the main part of the sed command (so I don't have to worry about the exclamation mark & backslashes), but I *do* want `$NEWVERSION` to be expanded.
Modify to suit your script. | ```
awk -v change=1 -v newver=2.3.4 '
change && /version/ {sub(/>[^<]+/, ">" newver)}
/<\/?dependencies>/ {change = !change}
{print}
'
``` |
10,002,937 | I have some pom files in my project with the following structure
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>xparent</artifactId>
<groupId>y</groupId>
<version>2.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>someparent</artifactId>
<version>x.x.x-needs_change</version>
<packaging>pom</packaging>
<name>some name</name>
<description>some description</description>
<url>myurl</url>
<modules>
<module>mymodules</module>
</modules>
<properties>
<my.version>x.x.x-needs_change</my.version>
</properties>
<dependencies>
<dependency>
<groupId>hhhhh</groupId>
<artifactId>hhhhh</artifactId>
<version>x.x.x-should not change</version>
</dependency>
</dependencies>
</project>
```
I am using sed to give the current version as input and change it to a new version given. But I do not want to change version within dependency block. How do I do this?
I do not want to go the maven version plugin route. I have tried it and it does not suit my requirements.
I prefer sed / python script.
Thanks | 2012/04/03 | [
"https://Stackoverflow.com/questions/10002937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164061/"
] | To parse and modify XML - you really should use a xml aware parser, such as [lxml](http://lxml.de/parsing.html) instead of text tools such as `sed` or `awk`
I assume that your POM files are indeed valid POM files, i.e. they have the enclosing `<project>` tag as well.
```
>>> t = """<project>
... <parent>
... <artifactID> </artifactID>
... <groupID> </groupID>
... <version>2.0.0</version>
... </parent>
...
... <properties>
... <version>2.0.0</version>
... </properties>
...
... <dependencies>
... <dependency>
... <version>2.0.0</version>
... </dependency>
... </dependencies></project>
... """
>>> from lxml import etree
>>> r = etree.fromstring(t)
>>> r.xpath("//parent/version")[0].text = "3.0"
>>> r.xpath("//properties/version")[0].text = "3.0"
>>> print(etree.tostring(r))
<project>
<parent>
<artifactID> </artifactID>
<groupID> </groupID>
<version>3.0</version>
</parent>
<properties>
<version>3.0</version>
</properties>
<dependencies>
<dependency>
<version>2.0.0</version>
</dependency>
</dependencies></project>
``` | ```
nawk '{
a=$0;
getline;
if($0!~/depend/ && a!~/version/)
{gsub(/2.0.0/,"1.0.0",$0);print a"\n"$0}
else print a"\n"$0
}' file3
```
Below is the test:
```
pearl.302> cat file3
<parent>
<aritifactID> </artifactID>
<groupID> </groupID>
<version>2.0.0</version>
</parent>
<properties>
<version>2.0.0</version>
</properties>
<dependencies>
<dependency>
<version>2.0.0</version>
</dependency>
</dependencies>
pearl.303> nawk '{a=$0;
getline;
if($0!~/depend/ && a!~/version/)
{gsub(/2.0.0/,"1.0.0",$0);print a"\n"$0}
else print a"\n"$0 }' file3
<parent>
<aritifactID> </artifactID>
<groupID> </groupID>
<version>1.0.0</version>
</parent>
<properties>
<version>1.0.0</version>
</properties>
<dependencies>
<dependency>
<version>2.0.0</version>
</dependency>
</dependencies>
``` |
10,002,937 | I have some pom files in my project with the following structure
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>xparent</artifactId>
<groupId>y</groupId>
<version>2.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>someparent</artifactId>
<version>x.x.x-needs_change</version>
<packaging>pom</packaging>
<name>some name</name>
<description>some description</description>
<url>myurl</url>
<modules>
<module>mymodules</module>
</modules>
<properties>
<my.version>x.x.x-needs_change</my.version>
</properties>
<dependencies>
<dependency>
<groupId>hhhhh</groupId>
<artifactId>hhhhh</artifactId>
<version>x.x.x-should not change</version>
</dependency>
</dependencies>
</project>
```
I am using sed to give the current version as input and change it to a new version given. But I do not want to change version within dependency block. How do I do this?
I do not want to go the maven version plugin route. I have tried it and it does not suit my requirements.
I prefer sed / python script.
Thanks | 2012/04/03 | [
"https://Stackoverflow.com/questions/10002937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164061/"
] | To parse and modify XML - you really should use a xml aware parser, such as [lxml](http://lxml.de/parsing.html) instead of text tools such as `sed` or `awk`
I assume that your POM files are indeed valid POM files, i.e. they have the enclosing `<project>` tag as well.
```
>>> t = """<project>
... <parent>
... <artifactID> </artifactID>
... <groupID> </groupID>
... <version>2.0.0</version>
... </parent>
...
... <properties>
... <version>2.0.0</version>
... </properties>
...
... <dependencies>
... <dependency>
... <version>2.0.0</version>
... </dependency>
... </dependencies></project>
... """
>>> from lxml import etree
>>> r = etree.fromstring(t)
>>> r.xpath("//parent/version")[0].text = "3.0"
>>> r.xpath("//properties/version")[0].text = "3.0"
>>> print(etree.tostring(r))
<project>
<parent>
<artifactID> </artifactID>
<groupID> </groupID>
<version>3.0</version>
</parent>
<properties>
<version>3.0</version>
</properties>
<dependencies>
<dependency>
<version>2.0.0</version>
</dependency>
</dependencies></project>
``` | ```
awk -v change=1 -v newver=2.3.4 '
change && /version/ {sub(/>[^<]+/, ">" newver)}
/<\/?dependencies>/ {change = !change}
{print}
'
``` |
10,211,188 | I am using python2.7 and lxml. My code is as below
```
import urllib
from lxml import html
def get_value(el):
return get_text(el, 'value') or el.text_content()
response = urllib.urlopen('http://www.edmunds.com/dealerships/Texas/Frisco/DavidMcDavidHondaofFrisco/fullsales-504210667.html').read()
dom = html.fromstring(response)
try:
description = get_value(dom.xpath("//div[@class='description item vcard']")[0].xpath(".//p[@class='sales-review-paragraph loose-spacing']")[0])
except IndexError, e:
description = ''
```
The code crashes inside the try, giving an error
```
UnicodeDecodeError at /
'utf8' codec can't decode byte 0x92 in position 85: invalid start byte
```
The string that could not be encoded/decoded was: ouldn�t be
I have tried using a lot of techniques including .encode('utf8'), but none does solve the problem. I have 2 question:
1. How to solve this problem
2. How can my app crash when the problem code is between a try except | 2012/04/18 | [
"https://Stackoverflow.com/questions/10211188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952787/"
] | Your except clause only handles exceptions of the IndexError type. The problem was a UnicodeDecodeError, which is not an IndexError - so the exception is not handled by that except clause.
It's also not clear what 'get\_value' does, and that may well be where the actual problem is arising. | 1. * skip chars on Error, or decode it correctly to unicode.
2. * you only catch IndexError, not UnicodeDecodeError |
10,211,188 | I am using python2.7 and lxml. My code is as below
```
import urllib
from lxml import html
def get_value(el):
return get_text(el, 'value') or el.text_content()
response = urllib.urlopen('http://www.edmunds.com/dealerships/Texas/Frisco/DavidMcDavidHondaofFrisco/fullsales-504210667.html').read()
dom = html.fromstring(response)
try:
description = get_value(dom.xpath("//div[@class='description item vcard']")[0].xpath(".//p[@class='sales-review-paragraph loose-spacing']")[0])
except IndexError, e:
description = ''
```
The code crashes inside the try, giving an error
```
UnicodeDecodeError at /
'utf8' codec can't decode byte 0x92 in position 85: invalid start byte
```
The string that could not be encoded/decoded was: ouldn�t be
I have tried using a lot of techniques including .encode('utf8'), but none does solve the problem. I have 2 question:
1. How to solve this problem
2. How can my app crash when the problem code is between a try except | 2012/04/18 | [
"https://Stackoverflow.com/questions/10211188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952787/"
] | The page is being served up with `charset=ISO-8859-1`. Decode from that to unicode.
[![Snapshot of details from a browser. Credit @Old Panda]](https://i.stack.imgur.com/jVHTy.png) | 1. * skip chars on Error, or decode it correctly to unicode.
2. * you only catch IndexError, not UnicodeDecodeError |
10,211,188 | I am using python2.7 and lxml. My code is as below
```
import urllib
from lxml import html
def get_value(el):
return get_text(el, 'value') or el.text_content()
response = urllib.urlopen('http://www.edmunds.com/dealerships/Texas/Frisco/DavidMcDavidHondaofFrisco/fullsales-504210667.html').read()
dom = html.fromstring(response)
try:
description = get_value(dom.xpath("//div[@class='description item vcard']")[0].xpath(".//p[@class='sales-review-paragraph loose-spacing']")[0])
except IndexError, e:
description = ''
```
The code crashes inside the try, giving an error
```
UnicodeDecodeError at /
'utf8' codec can't decode byte 0x92 in position 85: invalid start byte
```
The string that could not be encoded/decoded was: ouldn�t be
I have tried using a lot of techniques including .encode('utf8'), but none does solve the problem. I have 2 question:
1. How to solve this problem
2. How can my app crash when the problem code is between a try except | 2012/04/18 | [
"https://Stackoverflow.com/questions/10211188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952787/"
] | Your except clause only handles exceptions of the IndexError type. The problem was a UnicodeDecodeError, which is not an IndexError - so the exception is not handled by that except clause.
It's also not clear what 'get\_value' does, and that may well be where the actual problem is arising. | 1. decode the response to unicode, properly handling errors (ignore on error) before parsing with fromhtml.
2. catch the UnicodeDecodeError, or all errors. |
10,211,188 | I am using python2.7 and lxml. My code is as below
```
import urllib
from lxml import html
def get_value(el):
return get_text(el, 'value') or el.text_content()
response = urllib.urlopen('http://www.edmunds.com/dealerships/Texas/Frisco/DavidMcDavidHondaofFrisco/fullsales-504210667.html').read()
dom = html.fromstring(response)
try:
description = get_value(dom.xpath("//div[@class='description item vcard']")[0].xpath(".//p[@class='sales-review-paragraph loose-spacing']")[0])
except IndexError, e:
description = ''
```
The code crashes inside the try, giving an error
```
UnicodeDecodeError at /
'utf8' codec can't decode byte 0x92 in position 85: invalid start byte
```
The string that could not be encoded/decoded was: ouldn�t be
I have tried using a lot of techniques including .encode('utf8'), but none does solve the problem. I have 2 question:
1. How to solve this problem
2. How can my app crash when the problem code is between a try except | 2012/04/18 | [
"https://Stackoverflow.com/questions/10211188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952787/"
] | The page is being served up with `charset=ISO-8859-1`. Decode from that to unicode.
[![Snapshot of details from a browser. Credit @Old Panda]](https://i.stack.imgur.com/jVHTy.png) | Your except clause only handles exceptions of the IndexError type. The problem was a UnicodeDecodeError, which is not an IndexError - so the exception is not handled by that except clause.
It's also not clear what 'get\_value' does, and that may well be where the actual problem is arising. |
10,211,188 | I am using python2.7 and lxml. My code is as below
```
import urllib
from lxml import html
def get_value(el):
return get_text(el, 'value') or el.text_content()
response = urllib.urlopen('http://www.edmunds.com/dealerships/Texas/Frisco/DavidMcDavidHondaofFrisco/fullsales-504210667.html').read()
dom = html.fromstring(response)
try:
description = get_value(dom.xpath("//div[@class='description item vcard']")[0].xpath(".//p[@class='sales-review-paragraph loose-spacing']")[0])
except IndexError, e:
description = ''
```
The code crashes inside the try, giving an error
```
UnicodeDecodeError at /
'utf8' codec can't decode byte 0x92 in position 85: invalid start byte
```
The string that could not be encoded/decoded was: ouldn�t be
I have tried using a lot of techniques including .encode('utf8'), but none does solve the problem. I have 2 question:
1. How to solve this problem
2. How can my app crash when the problem code is between a try except | 2012/04/18 | [
"https://Stackoverflow.com/questions/10211188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952787/"
] | The page is being served up with `charset=ISO-8859-1`. Decode from that to unicode.
[![Snapshot of details from a browser. Credit @Old Panda]](https://i.stack.imgur.com/jVHTy.png) | 1. decode the response to unicode, properly handling errors (ignore on error) before parsing with fromhtml.
2. catch the UnicodeDecodeError, or all errors. |
19,637,346 | I have python project that is already built based on Scons.
I am trying to use Eclipse IDE and Pydev to fix some bugs in the source code.
I have installed Eclispe Sconsolidator plugin.
My project is like below
Project A
all source codes including Sconscript file which defines all the tager, environmet etc.
Eclipse provide me with Add Scons nature to the project. Once added the Scons automatically picks up my Sconscript file and executes.
```
== Running SCons at 10/28/13 1:59 PM ==
Command line: /opt/gcdistro/app/scons/2.3.0/bin/scons -u --jobs=16
scons: Reading SConscript files.
```
I want to know how can I place breakpoints in some of the .py files that is a part of my project which Scons is executing. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19637346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1845278/"
] | **Gateway Pattern**
>
> A gateway encapsulates the semantic gap between the object-oriented
> domain layer and the relation-oriented persistence layer.
>
>
>
Definition taken from [here](http://www.cs.sjsu.edu/~pearce/modules/patterns/enterprise/persistence/gateway.htm).
The Gateway in your example is also called a "Service". The service layer is important because it provides a higher abstraction and a more "holistic" way in dealing with a Person entity.
The reason for this "extra" layer is the other objects in the system that are connected to a Person. For example, say there are `Car` objects and each Person may have a Car. Now, when we sell a car we should update the "owner" field, further you'll want to do the same for the Person objects that are involved (seller/buyer).
In order to achieve this "cascading" in an OO manner (without coupling the objects implementations) `BuyCarService` will update the new owners: the service will call `CarDAO` and `PersonDAO` in order to update the relevant fields in the DB so that the DAOs won't have to "know" each other and hence decouple the implementations.
Hope this makes things clearer. | Most of the Design patterns explanations become confusing at some time or other because originally it was named and explained by someone but in due course of time several other similar patterns come into existence which have similar usage and explanation but very little difference. This subtle difference then becomes a source of debates:-). Concerning Gateway pattern, here is what is Martin Fowler mentions in Catalogs of Enterprise Application architecture.I am straight quoting from [here](http://martinfowler.com/eaaCatalog/gateway.html)
>
> "Gateway - An object that encapsulates access to an external system or
> resource."
>
>
> Interesting software rarely lives in isolation. Even the purest
> object-oriented system often has to deal with things that aren't
> objects, such as relational data-base tables, CICS transactions, and
> XML data structures.
>
>
> When accessing external resources like this, you'll usually get APIs
> for them. However, these APIs are naturally going to be somewhat
> complicated because they take the nature of the resource into account.
> Anyone who needs to under-stand a resource needs to understand its API
> - whether JDBC and SQL for rela-tional databases or W3C or JDOM for XML. Not only does this make the software harder to understand, it
> also makes it much harder to change should you shift some data from a
> relational database to an XML message at some point in the future.
>
>
> The answer is so common that it's hardly worth stating. Wrap all the
> special API code into a class whose interface looks like a regular
> object. Other objects access the resource through this Gateway, which
> translates the simple method calls into the appropriate specialized
> API.
>
>
> |
19,637,346 | I have python project that is already built based on Scons.
I am trying to use Eclipse IDE and Pydev to fix some bugs in the source code.
I have installed Eclispe Sconsolidator plugin.
My project is like below
Project A
all source codes including Sconscript file which defines all the tager, environmet etc.
Eclipse provide me with Add Scons nature to the project. Once added the Scons automatically picks up my Sconscript file and executes.
```
== Running SCons at 10/28/13 1:59 PM ==
Command line: /opt/gcdistro/app/scons/2.3.0/bin/scons -u --jobs=16
scons: Reading SConscript files.
```
I want to know how can I place breakpoints in some of the .py files that is a part of my project which Scons is executing. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19637346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1845278/"
] | **Gateway Pattern**
>
> A gateway encapsulates the semantic gap between the object-oriented
> domain layer and the relation-oriented persistence layer.
>
>
>
Definition taken from [here](http://www.cs.sjsu.edu/~pearce/modules/patterns/enterprise/persistence/gateway.htm).
The Gateway in your example is also called a "Service". The service layer is important because it provides a higher abstraction and a more "holistic" way in dealing with a Person entity.
The reason for this "extra" layer is the other objects in the system that are connected to a Person. For example, say there are `Car` objects and each Person may have a Car. Now, when we sell a car we should update the "owner" field, further you'll want to do the same for the Person objects that are involved (seller/buyer).
In order to achieve this "cascading" in an OO manner (without coupling the objects implementations) `BuyCarService` will update the new owners: the service will call `CarDAO` and `PersonDAO` in order to update the relevant fields in the DB so that the DAOs won't have to "know" each other and hence decouple the implementations.
Hope this makes things clearer. | The **Gateway design pattern** is useful when you want to work with a complex SDK, Library or API. To work with them you may need some implementation that lower layers don't have to know about them and of course, that is not important for other layers. In this case, the Gateway design pattern is the best solution. Yo implement what you want with any SDK or library and after that with a contract, other project layers can work easily with the gateway. And if someday you decide to change the mentioned SDK or API, it doesn't affect to the whole of the project. You simply can change the gateway implementation and the contract will be unchanged for the other layers. |
19,637,346 | I have python project that is already built based on Scons.
I am trying to use Eclipse IDE and Pydev to fix some bugs in the source code.
I have installed Eclispe Sconsolidator plugin.
My project is like below
Project A
all source codes including Sconscript file which defines all the tager, environmet etc.
Eclipse provide me with Add Scons nature to the project. Once added the Scons automatically picks up my Sconscript file and executes.
```
== Running SCons at 10/28/13 1:59 PM ==
Command line: /opt/gcdistro/app/scons/2.3.0/bin/scons -u --jobs=16
scons: Reading SConscript files.
```
I want to know how can I place breakpoints in some of the .py files that is a part of my project which Scons is executing. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19637346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1845278/"
] | Most of the Design patterns explanations become confusing at some time or other because originally it was named and explained by someone but in due course of time several other similar patterns come into existence which have similar usage and explanation but very little difference. This subtle difference then becomes a source of debates:-). Concerning Gateway pattern, here is what is Martin Fowler mentions in Catalogs of Enterprise Application architecture.I am straight quoting from [here](http://martinfowler.com/eaaCatalog/gateway.html)
>
> "Gateway - An object that encapsulates access to an external system or
> resource."
>
>
> Interesting software rarely lives in isolation. Even the purest
> object-oriented system often has to deal with things that aren't
> objects, such as relational data-base tables, CICS transactions, and
> XML data structures.
>
>
> When accessing external resources like this, you'll usually get APIs
> for them. However, these APIs are naturally going to be somewhat
> complicated because they take the nature of the resource into account.
> Anyone who needs to under-stand a resource needs to understand its API
> - whether JDBC and SQL for rela-tional databases or W3C or JDOM for XML. Not only does this make the software harder to understand, it
> also makes it much harder to change should you shift some data from a
> relational database to an XML message at some point in the future.
>
>
> The answer is so common that it's hardly worth stating. Wrap all the
> special API code into a class whose interface looks like a regular
> object. Other objects access the resource through this Gateway, which
> translates the simple method calls into the appropriate specialized
> API.
>
>
> | The **Gateway design pattern** is useful when you want to work with a complex SDK, Library or API. To work with them you may need some implementation that lower layers don't have to know about them and of course, that is not important for other layers. In this case, the Gateway design pattern is the best solution. Yo implement what you want with any SDK or library and after that with a contract, other project layers can work easily with the gateway. And if someday you decide to change the mentioned SDK or API, it doesn't affect to the whole of the project. You simply can change the gateway implementation and the contract will be unchanged for the other layers. |
35,601,754 | I want to encrypt a string in python. Every character in the char is mapped to some other character in the secret key. For example `'a'` is mapped to `'D'`, 'b' is mapped to `'d'`, `'c'` is mapped to `'1'` and so forth as shown below:
```
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
secretkey="Dd18Abz2EqNPWhYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
```
If I choose the string `"Lets meet at the usual place at 9 am"` the output must be `"oABjMWAABMDBMB2AMvjvDPMYPD1AMDBMGMDW"` | 2016/02/24 | [
"https://Stackoverflow.com/questions/35601754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5948577/"
] | **As for replacing multiple characters in a string**
You can use [`str.maketrans`](https://docs.python.org/3.5/library/stdtypes.html#str.maketrans) and [`str.translate`](https://docs.python.org/3.5/library/stdtypes.html#str.translate):
```
>>> char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
>>> secretkey = "Dd18Abz2EqNPWhYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
>>> trans = str.maketrans(char, secretkey)
>>> s = "Lets meet at the usual place at 9 am"
>>> s.translate(trans)
'0AvB WAAv Dv v2A tBtDP TPD1A Dv M DW'
```
or if you prefer to preserve only those in `char`:
```
>>> ''.join(c for c in s if c in char).translate(trans)
'0AvBWAAvDvv2AtBtDPTPD1ADvMDW'
```
**As for encrypting**
I would recommend using a dedicated library for that, such as [pycrypto](https://pypi.python.org/pypi/pycrypto). | Ok, I am making two assumptions here.
1. I think the output you expect is wrong, for instance `L` should be mapped to `0`, not to `o`, right?
2. I am assuming you want to ignore whitespace, since it is not included in your mapping.
So then the code would be:
```
to_encrypt = "Lets meet at the usual place at 9 am"
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
secretkey = "Dd18Abz2EqNPWhYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
encrypted = ""
for c in to_encrypt:
if c in char:
encrypted += secretkey[char.index(c)]
print(encrypted)
```
The output would be:
```
0AvBWAAvDvv2AtBtDPTPD1ADvMDW
``` |
15,750,681 | I'm writing a simple game in python(2.7) in pygame. In this game, I have to store 2D coordinates. The number of these items will start from 0 and increase by 2 in each step. They will increase up to ~6000. In each step I have to check whether 9 specific coordinates are among them, or not. I've tried to store them simply in a list as (x,y), but it is not efficient to search in such a list.
**How can I store these coordinates so it will be more efficient to search among them?**
What I was trying to do in each step:
```
# Assuming:
myList = []
co1 = (12.3,20.2) # and so on..
valuesToCheck = [co1,co2,co3,co4,co5,co6,co7,co8,co9]
# In each step:
# Adding 2 coordinates
myList.append((x1,y1))
myList.append((x2,y2))
# Searching 9 specific coordinates among all
for coordinate in valuesToCheck:
if coordinate in myList:
print "Hit!"
break
# Note that the valuesToCheck will change in each step.
del valuesToCheck[0]
valuesToCheck.append(co10)
```
Coordinates are floating point numbers, and their highest values are limited. They start from (0.0,0.0) to (1200.0,700.0).
I've searched about this but stored values were either string or constant numbers. | 2013/04/01 | [
"https://Stackoverflow.com/questions/15750681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2049320/"
] | Maintain a [set](http://docs.python.org/3.3/tutorial/datastructures.html#sets) alongside your list, or replacing the list entirely if you have no other use for it. Membership checking and adding are [O(1) on average](http://wiki.python.org/moin/TimeComplexity) for sets, so your overall algorithm will be O(N) compared to the O(N^2) of just using a list.
```
myList = []
mySet = set()
co1 = (12,20) # and so on..
valuesToCheck = [co1,co2,co3,co4,co5,co6,co7,co8,co9]
# In each step:
# Adding 2 coordinates
myList.append((x1,y1))
myList.append((x2,y2))
mySet.add((x1, y1))
mySet.add((x2, y2))
# Searching 9 specific coordinates among all
for coordinate in valuesToCheck:
if coordinate in mySet:
print "Hit!"
break
# Note that the valuesToCheck will change in each step.
del valuesToCheck[0]
valuesToCheck.append(co10)
``` | If I understand correctly, you're adding elements to `myList`, but never removing them. You're then testing every element of `valuesToCheck` for memebership in `myList`.
If that's the case, you could boost performance by converting myList to a set instead of a list. Testing for membership in a list is O(n), while testing for membership in a set is typically O(1).
Your syntax will remain mostly unchanged:
```
mySet = set()
# your code
# Adding 2 coordinates
mySet.add((x1,y1))
mySet.add((x2,y2))
# Searching 9 specific coordinates among all
for coordinate in valuesToCheck:
if coordinate in mySet:
print "Hit!"
break
# Note that the valuesToCheck will change in each step.
del valuesToCheck[0]
valuesToCheck.append(co10)
``` |
37,866,313 | I did `ls -l /usr/bin/python`
I got
[](https://i.stack.imgur.com/wvA2p.png)
How can I fix that red symbolic link ? | 2016/06/16 | [
"https://Stackoverflow.com/questions/37866313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480164/"
] | `ls -l /usr/bin/python` will only show the symbolic link.
Use `ls -l /usr/bin/ | grep python2.7` to see if `python2.7` is in the directory.
The output should be something like this:
```
lrwxrwxrwx 1 root root 9 Jun 3 16:39 python -> python2.7
lrwxrwxrwx 1 root root 9 Jun 3 16:39 python2 -> python2.7
-rwxr-xr-x 1 root root 3550168 Jun 3 02:29 python2.7
```
The above shows the binary `python2.7` and two symbolic links pointing to it. | You can enter
```
$which python
```
to see where your Python path is.
You can then use
```
$ln -s /thepathfromabove/python2.7 python
``` |
66,406,182 | I'm not the best with python and am trying to cipher shift text entered by the user. The way this cipher should work is disregarding symbols, numbers, etc. It also converts full stops to X's and must all be upper case. I currently have the code for that but am unsure as to how to take that converted text and shift it by a number given by the user. Not sure if this all makes sense, but any help would be greatly appreciated!
Here is my code:
```
def convert_to_Caesar(t):
#Remove all special characters and only show A-Z
t = re.sub("[^A-Za-z.]",'', t)
cipherText = ""
# Full stops are replaced with X's
for letter in t:
if letter == '.':
cipherText += 'X'
# Lower case is converted to upper case
else:
cipherText += letter.upper()
# Plain text is ciphered and returned
return cipherText
# User enters plain text to cipher
text = input("What do you want to cipher? ")
shift = int(input("How many positions to shift by? "))
print(convert_to_Caesar(text))
```
Thank you | 2021/02/28 | [
"https://Stackoverflow.com/questions/66406182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15299466/"
] | You can use ord()/chr() as suggested by @Girish Srivatsa:
```
alphabet_len = ord('Z') - ord('A') + 1
new_letter = chr((ord(letter.upper()) - ord('A') + shift) % alphabet_len + ord('A'))
```
But it might be cleaner if you just create a variable that holds your alphabet:
```
import string
alphabet = "".join(list(string.ascii_uppercase))
```
Then you look what you look up the position in your alphabet, add the positions, then look up what the new letter is:
```
pos = alphabet.find(letter.upper())
if pos == -1:
if letter == '.':
new_letter = 'X'
else:
# discard other symbols
new_letter = ''
else:
new_pos = (pos + shift) % len(alphabet)
new_letter = alphabet[new_pos]
```
Note, you cannot tell if 'X' in your cipher text a shifted letter or '.'. If you need to fix that, add '.' to your alphabet and remove the special case for '.' under `if pos == -1`. This becomes messy with chr()/ord() method. | If you want it to be formatted even more correctly, following all your rules but formatting in capitals and lowercase too. This shifts the dictionary, and runs if loops. I know you asked for all letters to be capitals, but this improves the code a little.
Output of Code:
```
Do you want to... 1. Encode, or 2. Decode? 1
This must be encoded! Please, Work!
5
Ymnx rzxy gj jshtiji! Uqjfxj, Btwp!
```
Code:
```
import time
def shift_dict(Caesar, Shift):
dic_len = len(Caesar)
Shift = Shift % dic_len
list_dic = [(k,v) for k, v in iter(Caesar.items())]
Shifted = {
list_dic[x][0]: list_dic[(x - Shift) % dic_len][1]
for x in range(dic_len)
}
return Shifted
def shift_dict2(Caesar, Shift):
dic_len = len(Caesar)
Shift = Shift % dic_len
list_dic = [(k,v) for k, v in iter(Caesar.items())]
Shifted = {
list_dic[x][0]: list_dic[(x - Shift) % dic_len][-1]
for x in range(dic_len)
}
return Shifted
UpperList = {
"A":0,
"B":1,
"C":2,
"D":3,
"E":4,
"F":5,
"G":6,
"H":7,
"I":8,
"J":9,
"K":10,
"L":11,
"M":12,
"N":13,
"O":14,
"P":15,
"Q":16,
"R":17,
"S":18,
"T":19,
"U":20,
"V":21,
"W":22,
"X":23,
"Y":24,
"Z":25
}
UpperCaesar = {
"A":"A",
"B":"B",
"C":"C",
"D":"D",
"E":"E",
"F":"F",
"G":"G",
"H":"H",
"I":"I",
"J":"J",
"K":"K",
"L":"L",
"M":"M",
"N":"N",
"O":"O",
"P":"P",
"Q":"Q",
"R":"R",
"S":"S",
"T":"T",
"U":"U",
"V":"V",
"W":"W",
"X":"X",
"Y":"Y",
"Z":"Z"
}
LowerList = {
"a":0,
"b":1,
"c":2,
"d":3,
"e":4,
"f":5,
"g":6,
"h":7,
"i":8,
"j":9,
"k":10,
"l":11,
"m":12,
"n":13,
"o":14,
"p":15,
"q":16,
"r":17,
"s":18,
"t":19,
"u":20,
"v":21,
"w":22,
"x":23,
"y":24,
"z":25
}
LowerCaesar = {
"a":"a",
"b":"b",
"c":"c",
"d":"d",
"e":"e",
"f":"f",
"g":"g",
"h":"h",
"i":"i",
"j":"j",
"k":"k",
"l":"l",
"m":"m",
"n":"n",
"o":"o",
"p":"p",
"q":"q",
"r":"r",
"s":"s",
"t":"t",
"u":"u",
"v":"v",
"w":"w",
"x":"x",
"y":"y",
"z":"z"
}
UpperList1 = {
"A":0,
"B":1,
"C":2,
"D":3,
"E":4,
"F":5,
"G":6,
"H":7,
"I":8,
"J":9,
"K":10,
"L":11,
"M":12,
"N":13,
"O":14,
"P":15,
"Q":16,
"R":17,
"S":18,
"T":19,
"U":20,
"V":21,
"W":22,
"X":23,
"Y":24,
"Z":25
}
UpperCaesar1 = {
"A":"A",
"B":"B",
"C":"C",
"D":"D",
"E":"E",
"F":"F",
"G":"G",
"H":"H",
"I":"I",
"J":"J",
"K":"K",
"L":"L",
"M":"M",
"N":"N",
"O":"O",
"P":"P",
"Q":"Q",
"R":"R",
"S":"S",
"T":"T",
"U":"U",
"V":"V",
"W":"W",
"X":"X",
"Y":"Y",
"Z":"Z"
}
LowerList1 = {
"a":0,
"b":1,
"c":2,
"d":3,
"e":4,
"f":5,
"g":6,
"h":7,
"i":8,
"j":9,
"k":10,
"l":11,
"m":12,
"n":13,
"o":14,
"p":15,
"q":16,
"r":17,
"s":18,
"t":19,
"u":20,
"v":21,
"w":22,
"x":23,
"y":24,
"z":25
}
LowerCaesar1 = {
"a":"a",
"b":"b",
"c":"c",
"d":"d",
"e":"e",
"f":"f",
"g":"g",
"h":"h",
"i":"i",
"j":"j",
"k":"k",
"l":"l",
"m":"m",
"n":"n",
"o":"o",
"p":"p",
"q":"q",
"r":"r",
"s":"s",
"t":"t",
"u":"u",
"v":"v",
"w":"w",
"x":"x",
"y":"y",
"z":"z"
}
Asker = int(input("Do you want to... 1. Encode, or 2. Decode? "))
if Asker == 1:
Plaintext = str(input(""))
OriginalShift = int(input(""))
Shift = OriginalShift*-1
UpperCaesar = shift_dict(UpperCaesar, Shift)
LowerCaesar = shift_dict(LowerCaesar, Shift)
Lister = []
X = 0
for i in range(len(Plaintext)):
if Plaintext[X].isalpha():
if Plaintext[X].isupper():
Lister.append(UpperCaesar[Plaintext[X]])
else:
Lister.append(LowerCaesar[Plaintext[X]])
else:
Lister.append(Plaintext[X])
X += 1
print(*Lister, sep = "")
elif Asker == 2:
Asker1 = int(input("Do you have the key (1), or not(2): "))
if Asker1 == 1:
Plaintext = str(input(""))
OriginalShift = int(input(""))
Shift = OriginalShift*-1
UpperCaesar = shift_dict(UpperCaesar, 26 - Shift)
LowerCaesar = shift_dict(LowerCaesar, 26 - Shift)
Lister = []
X = 0
for i in range(len(Plaintext)):
if Plaintext[X].isalpha():
if Plaintext[X].isupper():
Lister.append(UpperCaesar[Plaintext[X]])
else:
Lister.append(LowerCaesar[Plaintext[X]])
else:
Lister.append(Plaintext[X])
X += 1
print(*Lister, sep = "")
elif Asker1 == 2:
Plaintext = str(input(""))
OriginalShift = 0
for i in range(26):
UpperCaesar = shift_dict2(UpperCaesar, -1)
LowerCaesar = shift_dict2(LowerCaesar, -1)
Lister = []
X = 0
for i in range(len(Plaintext)):
if Plaintext[X].isalpha():
if Plaintext[X].isupper():
Lister.append(UpperCaesar[Plaintext[X]])
else:
Lister.append(LowerCaesar[Plaintext[X]])
else:
Lister.append(Plaintext[X])
X += 1
time.sleep(0.01)
print("With a shift of ", 25 - (OriginalShift*-1), ": ", *Lister, sep = "")
OriginalShift -= 1
``` |
66,894,868 | My results is only empty loop logs.
if i put manual in terminal this line command :
```
python3 -m PyInstaller --onefile --name SOCIAL_NETWORK_TEST --distpath packages/projectTest --workpath .cache/ app.py
```
then pack works fine.
Any suggestion.
```
bashCommand = "python3 -m PyInstaller --onefile --name " + self.engineConfig.currentProjectName + " --distpath " + "projects/" + self.engineConfig.currentProjectName + "/Package/" + " --workpath .cache/ main.py"
print("PACK DONE,")
# no expirience
import subprocess
process = subprocess.Popen(bashCommand.split(), stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
# self.myLogs = []
for line in iter(process.stdout.readline, b'\n'):
# self.testLog = str(line)
# self.LOGS.text = self.testLog
print ("PACKAGE:", str(line))
print("Package application for linux ended.")
``` | 2021/03/31 | [
"https://Stackoverflow.com/questions/66894868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513187/"
] | It seems you're running server and client in the same directory, and the server truncates the file before the client gets to read from it. | it works pefect for me with hello world but if you want to send a binary file maybe you can try base 64 |
21,940,911 | I'm trying to apply a ripple effect to an image in python.
I found Pillow's im.transform(im.size, Image.MESH,.... is it possible?
Maybe I have to load the image with numpy and apply the algorithm.
I also found this: <http://www.pygame.org/project-Water+Ripples-1239-.html>

another way manually but I don't know any algorithm. this is my start. it doesn't do anything...
```
#!/usr/bin/env python3
from PIL import Image
import sys
import numpy
import math
im = Image.open(sys.argv[1])
im.show()
matrix = numpy.asarray(im)
width = im.size[0]
height = im.size[1]
amplitude = ? # parameters
frequency = ?
matrix_dest = numpy.zeros((im.size[0],im.size[1],3))
for x in range(0, width):
for y in range(0, height):
pass # ç_ç
im2 = Image.fromarray(numpy.uint8(matrix_dest))
im2.show()
```
**EDIT:**
I'd really like to keep this structure (using pillow. I already use extensivly in my project and if I can I wouldn't add any other dependency) and not including scipi or matplotlib..
With the following code I have the distortion I wanted, but **colors** are screwed up.
Maybe I have to apply the distortion to **R,G,B planes** and then compose the result in one image.
Or **palettize** the image and then apply the original palette.
(Btw the image would be used as a texture to display moving water in a 3D environment.)
```
im = Image.open(sys.argv[1])
im.show()
m = numpy.asarray(im)
m2 = numpy.zeros((im.size[0],im.size[1],3))
width = im.size[0]
height = im.size[1]
A = m.shape[0] / 3.0
w = 1.0 / m.shape[1]
shift = lambda x: A * numpy.sin(2.0*numpy.pi*x * w)
for i in range(m.shape[0]):
print(int(shift(i)))
m2[:,i] = numpy.roll(m[:,i], int(shift(i)))
im2 = Image.fromarray(numpy.uint8(m2))
im2.show()
``` | 2014/02/21 | [
"https://Stackoverflow.com/questions/21940911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210984/"
] | You could use `np.roll` to rotate each row or column according to some sine function.
```
from scipy.misc import lena
import numpy as np
import matplotlib.pyplot as plt
img = lena()
A = img.shape[0] / 3.0
w = 2.0 / img.shape[1]
shift = lambda x: A * np.sin(2.0*np.pi*x * w)
for i in range(img.shape[0]):
img[:,i] = np.roll(img[:,i], int(shift(i)))
plt.imshow(img, cmap=plt.cm.gray)
plt.show()
```
 | Why don't you try something like:
```
# import scipy
# import numpy as np
for x in range(cols):
column = im[:,x]
y = np.floor(sin(x)*10)+10
kernel = np.zeros((20,1))
kernel[y] = 1
scipy.ndimage.filters.convolve(col,kernel,'nearest')
```
I threw this together just right now, so you'll need to tweak it a bit. The frequency of the sin is definitely too high, check [here](http://en.wikipedia.org/wiki/Sine_wave). But I think overall this should work. |
21,940,911 | I'm trying to apply a ripple effect to an image in python.
I found Pillow's im.transform(im.size, Image.MESH,.... is it possible?
Maybe I have to load the image with numpy and apply the algorithm.
I also found this: <http://www.pygame.org/project-Water+Ripples-1239-.html>

another way manually but I don't know any algorithm. this is my start. it doesn't do anything...
```
#!/usr/bin/env python3
from PIL import Image
import sys
import numpy
import math
im = Image.open(sys.argv[1])
im.show()
matrix = numpy.asarray(im)
width = im.size[0]
height = im.size[1]
amplitude = ? # parameters
frequency = ?
matrix_dest = numpy.zeros((im.size[0],im.size[1],3))
for x in range(0, width):
for y in range(0, height):
pass # ç_ç
im2 = Image.fromarray(numpy.uint8(matrix_dest))
im2.show()
```
**EDIT:**
I'd really like to keep this structure (using pillow. I already use extensivly in my project and if I can I wouldn't add any other dependency) and not including scipi or matplotlib..
With the following code I have the distortion I wanted, but **colors** are screwed up.
Maybe I have to apply the distortion to **R,G,B planes** and then compose the result in one image.
Or **palettize** the image and then apply the original palette.
(Btw the image would be used as a texture to display moving water in a 3D environment.)
```
im = Image.open(sys.argv[1])
im.show()
m = numpy.asarray(im)
m2 = numpy.zeros((im.size[0],im.size[1],3))
width = im.size[0]
height = im.size[1]
A = m.shape[0] / 3.0
w = 1.0 / m.shape[1]
shift = lambda x: A * numpy.sin(2.0*numpy.pi*x * w)
for i in range(m.shape[0]):
print(int(shift(i)))
m2[:,i] = numpy.roll(m[:,i], int(shift(i)))
im2 = Image.fromarray(numpy.uint8(m2))
im2.show()
``` | 2014/02/21 | [
"https://Stackoverflow.com/questions/21940911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210984/"
] | Why don't you try something like:
```
# import scipy
# import numpy as np
for x in range(cols):
column = im[:,x]
y = np.floor(sin(x)*10)+10
kernel = np.zeros((20,1))
kernel[y] = 1
scipy.ndimage.filters.convolve(col,kernel,'nearest')
```
I threw this together just right now, so you'll need to tweak it a bit. The frequency of the sin is definitely too high, check [here](http://en.wikipedia.org/wiki/Sine_wave). But I think overall this should work. | I had a similar problem where sometimes the colors appear to be messed up (getting some weird red lines) after applying the sin when attempting the proposed solutions here. Couldn't resolve it.
I understand the original poster doesn't want more dependencies if possible, but for those unrestricted, here is a an alternative sample solution provided by scikit docs:
<http://scikit-image.org/docs/dev/auto_examples/transform/plot_piecewise_affine.html#sphx-glr-auto-examples-transform-plot-piecewise-affine-py>
Copying from the doc above:
```
import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import PiecewiseAffineTransform, warp
from skimage import data
image = data.astronaut()
rows, cols = image.shape[0], image.shape[1]
src_cols = np.linspace(0, cols, 20)
src_rows = np.linspace(0, rows, 10)
src_rows, src_cols = np.meshgrid(src_rows, src_cols)
src = np.dstack([src_cols.flat, src_rows.flat])[0]
# add sinusoidal oscillation to row coordinates
dst_rows = src[:, 1] - np.sin(np.linspace(0, 3 * np.pi, src.shape[0])) * 50
dst_cols = src[:, 0]
dst_rows *= 1.5
dst_rows -= 1.5 * 50
dst = np.vstack([dst_cols, dst_rows]).T
tform = PiecewiseAffineTransform()
tform.estimate(src, dst)
out_rows = image.shape[0] - 1.5 * 50
out_cols = cols
out = warp(image, tform, output_shape=(out_rows, out_cols))
fig, ax = plt.subplots()
ax.imshow(out)
ax.plot(tform.inverse(src)[:, 0], tform.inverse(src)[:, 1], '.b')
ax.axis((0, out_cols, out_rows, 0))
plt.show()
``` |
21,940,911 | I'm trying to apply a ripple effect to an image in python.
I found Pillow's im.transform(im.size, Image.MESH,.... is it possible?
Maybe I have to load the image with numpy and apply the algorithm.
I also found this: <http://www.pygame.org/project-Water+Ripples-1239-.html>

another way manually but I don't know any algorithm. this is my start. it doesn't do anything...
```
#!/usr/bin/env python3
from PIL import Image
import sys
import numpy
import math
im = Image.open(sys.argv[1])
im.show()
matrix = numpy.asarray(im)
width = im.size[0]
height = im.size[1]
amplitude = ? # parameters
frequency = ?
matrix_dest = numpy.zeros((im.size[0],im.size[1],3))
for x in range(0, width):
for y in range(0, height):
pass # ç_ç
im2 = Image.fromarray(numpy.uint8(matrix_dest))
im2.show()
```
**EDIT:**
I'd really like to keep this structure (using pillow. I already use extensivly in my project and if I can I wouldn't add any other dependency) and not including scipi or matplotlib..
With the following code I have the distortion I wanted, but **colors** are screwed up.
Maybe I have to apply the distortion to **R,G,B planes** and then compose the result in one image.
Or **palettize** the image and then apply the original palette.
(Btw the image would be used as a texture to display moving water in a 3D environment.)
```
im = Image.open(sys.argv[1])
im.show()
m = numpy.asarray(im)
m2 = numpy.zeros((im.size[0],im.size[1],3))
width = im.size[0]
height = im.size[1]
A = m.shape[0] / 3.0
w = 1.0 / m.shape[1]
shift = lambda x: A * numpy.sin(2.0*numpy.pi*x * w)
for i in range(m.shape[0]):
print(int(shift(i)))
m2[:,i] = numpy.roll(m[:,i], int(shift(i)))
im2 = Image.fromarray(numpy.uint8(m2))
im2.show()
``` | 2014/02/21 | [
"https://Stackoverflow.com/questions/21940911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210984/"
] | You could use `np.roll` to rotate each row or column according to some sine function.
```
from scipy.misc import lena
import numpy as np
import matplotlib.pyplot as plt
img = lena()
A = img.shape[0] / 3.0
w = 2.0 / img.shape[1]
shift = lambda x: A * np.sin(2.0*np.pi*x * w)
for i in range(img.shape[0]):
img[:,i] = np.roll(img[:,i], int(shift(i)))
plt.imshow(img, cmap=plt.cm.gray)
plt.show()
```
 | I had a similar problem where sometimes the colors appear to be messed up (getting some weird red lines) after applying the sin when attempting the proposed solutions here. Couldn't resolve it.
I understand the original poster doesn't want more dependencies if possible, but for those unrestricted, here is a an alternative sample solution provided by scikit docs:
<http://scikit-image.org/docs/dev/auto_examples/transform/plot_piecewise_affine.html#sphx-glr-auto-examples-transform-plot-piecewise-affine-py>
Copying from the doc above:
```
import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import PiecewiseAffineTransform, warp
from skimage import data
image = data.astronaut()
rows, cols = image.shape[0], image.shape[1]
src_cols = np.linspace(0, cols, 20)
src_rows = np.linspace(0, rows, 10)
src_rows, src_cols = np.meshgrid(src_rows, src_cols)
src = np.dstack([src_cols.flat, src_rows.flat])[0]
# add sinusoidal oscillation to row coordinates
dst_rows = src[:, 1] - np.sin(np.linspace(0, 3 * np.pi, src.shape[0])) * 50
dst_cols = src[:, 0]
dst_rows *= 1.5
dst_rows -= 1.5 * 50
dst = np.vstack([dst_cols, dst_rows]).T
tform = PiecewiseAffineTransform()
tform.estimate(src, dst)
out_rows = image.shape[0] - 1.5 * 50
out_cols = cols
out = warp(image, tform, output_shape=(out_rows, out_cols))
fig, ax = plt.subplots()
ax.imshow(out)
ax.plot(tform.inverse(src)[:, 0], tform.inverse(src)[:, 1], '.b')
ax.axis((0, out_cols, out_rows, 0))
plt.show()
``` |
64,553,669 | Does anyone know why I get an indentation error even though it (should) be correct?
```
while not stop:
try:
response += sock.recv(buffer_size)
if header not in response:
print("error in message format")
return # this is where I get the error
except socket.timeout:
stop = True
```
Error Code `python3 ueb02.py localhost 31000 File "ueb02.py", line 40 return ^ SyntaxError: 'return' outside function make: *** [run] Error 1`
**edit:** Thanks for the answers, @balderman's approach solved my problem. Thanks to everyone who contributed here :D | 2020/10/27 | [
"https://Stackoverflow.com/questions/64553669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12781947/"
] | If you want to delete the command executing message, like `prefix test_welcome`, you can use `await ctx.message.delete()`. | You can use `await ctx.message.delete`, either way, i recommend you to read the [documentation](https://discordpy.readthedocs.io/en/latest/). |
17,610,811 | I want to make crontab where script occurs at different minutes for each hour like this
`35 1,8,12,15,31 16,18,21 * * 0,1,2,3,4,5,6 python backup.py`
I want script to run at `16hour and 31 minutes` but it is giving me error bad hour
i want the cron occur at
`1:35am` , then `16:31`, then `21:45` | 2013/07/12 | [
"https://Stackoverflow.com/questions/17610811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667349/"
] | As there is not a pattern that can match the three times, it is not possible to schedule that just with one crontab expression. You will have to use three:
```
45 21 * * * python backup.py
31 16 * * * python backup.py
35 1 * * * python backup.py
```
Note also that `python backup.py` will probably not work. You have to define full path for both files and binaries:
```
35 1 * * * /usr/bin/python /your/dir/backup.py
```
Where `/usr/bin/python` or similar can be obtained with `which python`. | If the system which you are on has systemd, You can look into systemd timers(<https://www.freedesktop.org/software/systemd/man/systemd.time.html>). Then you might be able to achieve the randomness using the RandomizedDelaySec setting and an OnCalendar setting which will schedule the service to run every hour or interval you set plus will generate a RandomizedDelaySec at every run so that the interval is random. |
21,192,133 | Let's say I have a program that uses a .txt file to store data it needs to operate. Because it's a very large amount of data (just go with it) in the text file I was to use a generator rather than an iterator to go through the data in it so that my program leaves as much space as possible. Let's just say (I know this isn't secure) that it's a list of usernames. So my code would look like this (using python 3.3).
```
for x in range LenOfFile:
id = file.readlines(x)
if username == id:
validusername = True
#ask for a password
if validusername == True and validpassword == True:
pass
else:
print("Invalid Username")
```
Assume that valid password is set to True or False where I ask for a password. My question is, since I don't want to take up all of the RAM I don't want to use readlines() to get the whole thing, and with the code here I only take a very small amount of RAM at any given time. However, I am not sure how I would get the number of lines in the file (assume I cannot find the number of lines and add to it as new users arrive). Is there a way Python can do this without reading the entire file and storing it at once? I already tried `len()`, which apparently doesn't work on text files but was worth a try. The one way I have thought of to do this is not too great, it involves just using readlines one line at a time in a range so big the text file must be smaller, and then continuing when I get an error. I would prefer not to use this way, so any suggestions would be appreciated. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21192133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945577/"
] | You can just iterate over the file handle directly, which will then iterate over it line-by-line:
```
for line in file:
if username == line.strip():
validusername = True
break
```
Other than that, you can’t really tell how many lines a file has without looking at it completely. You do know how big a file is, and you could make some assumptions on the character count for example (UTF-8 ruins that though :P); but you don’t know how long each line is without seeing it, so you don’t know where the line breaks are and as such can’t tell how many lines there are in total. You still would have to look at every character one-by-one to see if a new line begins or not.
So instead of that, we just iterate over the file, and stop once whenever we read a whole line—that’s when the loop body executes—and then we continue looking from that position in the file for the next line break, and so on. | If you want number of lines in a file so badly, why don't you use `len`
```
with open("filename") as f:
num = len(f.readlines())
``` |
21,192,133 | Let's say I have a program that uses a .txt file to store data it needs to operate. Because it's a very large amount of data (just go with it) in the text file I was to use a generator rather than an iterator to go through the data in it so that my program leaves as much space as possible. Let's just say (I know this isn't secure) that it's a list of usernames. So my code would look like this (using python 3.3).
```
for x in range LenOfFile:
id = file.readlines(x)
if username == id:
validusername = True
#ask for a password
if validusername == True and validpassword == True:
pass
else:
print("Invalid Username")
```
Assume that valid password is set to True or False where I ask for a password. My question is, since I don't want to take up all of the RAM I don't want to use readlines() to get the whole thing, and with the code here I only take a very small amount of RAM at any given time. However, I am not sure how I would get the number of lines in the file (assume I cannot find the number of lines and add to it as new users arrive). Is there a way Python can do this without reading the entire file and storing it at once? I already tried `len()`, which apparently doesn't work on text files but was worth a try. The one way I have thought of to do this is not too great, it involves just using readlines one line at a time in a range so big the text file must be smaller, and then continuing when I get an error. I would prefer not to use this way, so any suggestions would be appreciated. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21192133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945577/"
] | You can just iterate over the file handle directly, which will then iterate over it line-by-line:
```
for line in file:
if username == line.strip():
validusername = True
break
```
Other than that, you can’t really tell how many lines a file has without looking at it completely. You do know how big a file is, and you could make some assumptions on the character count for example (UTF-8 ruins that though :P); but you don’t know how long each line is without seeing it, so you don’t know where the line breaks are and as such can’t tell how many lines there are in total. You still would have to look at every character one-by-one to see if a new line begins or not.
So instead of that, we just iterate over the file, and stop once whenever we read a whole line—that’s when the loop body executes—and then we continue looking from that position in the file for the next line break, and so on. | Yes, the good news is you can find number of lines in a text file without readlines, for line in file, etc. More specifically in python you can use byte functions, random access, parallel operation, and regular expressions, instead of slow sequential text line processing. Parallel text file like CSV file line counter is particularly suitable for SSD devices which have fast random access, when combined with a many processor cores. I used a 16 core system with SSD to store the Higgs Boson dataset as a standard file which you can go download to test on. Even more specifically here are fragments from working code to get you started. You are welcome to freely copy and use but if you do then please cite my work thank you:
```
import re
from argparse import ArgumentParser
from multiprocessing import Pool
from itertools import repeat
from os import stat
unitTest = 0
fileName = None
balanceFactor = 2
numProcesses = 1
if __name__ == '__main__':
argparser = ArgumentParser(description='Parallel text file like CSV file line counter is particularly suitable for SSD which have fast random access')
argparser.add_argument('--unitTest', default=unitTest, type=int, required=False, help='0:False 1:True.')
argparser.add_argument('--fileName', default=fileName, required=False, help='')
argparser.add_argument('--balanceFactor', default=balanceFactor, type=int, required=False, help='integer: 1 or 2 or 3 are typical')
argparser.add_argument('--numProcesses', default=numProcesses, type=int, required=False, help='integer: 1 or more. Best when matched to number of physical CPU cores.')
cmd = vars(argparser.parse_args())
unitTest=cmd['unitTest']
fileName=cmd['fileName']
balanceFactor=cmd['balanceFactor']
numProcesses=cmd['numProcesses']
#Do arithmetic to divide partitions into startbyte, endbyte strips among workers (2 lists of int)
#Best number of strips to use is 2x to 3x number of workers, for workload balancing
#import numpy as np # long heavy import but i love numpy syntax
def PartitionDataToWorkers(workers, items, balanceFactor=2):
strips = balanceFactor * workers
step = int(round(float(items)/strips))
startPos = list(range(1, items+1, step))
if len(startPos) > strips:
startPos = startPos[:-1]
endPos = [x + step - 1 for x in startPos]
endPos[-1] = items
return startPos, endPos
def ReadFileSegment(startByte, endByte, fileName, searchChar='\n'): # counts number of searchChar appearing in the byte range
with open(fileName, 'r') as f:
f.seek(startByte-1) # seek is initially at byte 0 and then moves forward the specified amount, so seek(5) points at the 6th byte.
bytes = f.read(endByte - startByte + 1)
cnt = len(re.findall(searchChar, bytes)) # findall with implicit compiling runs just as fast here as re.compile once + re.finditer many times.
return cnt
if 0 == unitTest:
# Run app, not unit tests.
fileBytes = stat(fileName).st_size # Read quickly from OS how many bytes are in a text file
startByte, endByte = PartitionDataToWorkers(workers=numProcesses, items=fileBytes, balanceFactor=balanceFactor)
p = Pool(numProcesses)
partialSum = p.starmap(ReadFileSegment, zip(startByte, endByte, repeat(fileName))) # startByte is already a list. fileName is made into a same-length list of duplicates values.
globalSum = sum(partialSum)
print(globalSum)
else:
print("Running unit tests") # Bash commands like: head --bytes 96 beer.csv are how I found the correct values.
fileName='beer.csv' # byte 98 is a newline
assert(8==ReadFileSegment(1, 288, fileName))
assert(1==ReadFileSegment(1, 100, fileName))
assert(0==ReadFileSegment(1, 97, fileName))
assert(1==ReadFileSegment(97, 98, fileName))
assert(1==ReadFileSegment(98, 99, fileName))
assert(0==ReadFileSegment(99, 99, fileName))
assert(1==ReadFileSegment(98, 98, fileName))
assert(0==ReadFileSegment(97, 97, fileName))
print("OK")
```
The bash wc program is slightly faster but you wanted pure python, and so did I. Below is some performance testing results. That said if you change some of this code to use cython or something you might even get some more speed.
```
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000
real 0m2.257s
user 0m12.088s
sys 0m20.512s
HP-Z820:/mnt/fastssd/fast_file_reader$ time wc -l HIGGS.csv
11000000 HIGGS.csv
real 0m1.820s
user 0m0.364s
sys 0m1.456s
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000
real 0m2.256s
user 0m10.696s
sys 0m19.952s
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=1 --balanceFactor=1
11000000
real 0m17.380s
user 0m11.124s
sys 0m6.272s
```
Conclusion: The speed is good for a pure python program compared to a C program. However, it’s not good enough to use the pure python program over the C program.
I wondered if compiling the regex just one time and passing it to all workers will improve speed. Answer: Regex pre-compiling does NOT help in this application. I suppose the reason is that the overhead of process serialization and creation for all the workers is dominating.
One more thing. Does parallel CSV file reading even help, I wondered? Is the disk the bottleneck, or is it the CPU? Oh yes, yes it does. Parallel file reading works quite well. Well there you go!
Data science is a typical use case for pure python. I like to use python (jupyter) notebooks, and I like to keep all code in the notebook rather than use bash scripts when possible. Finding the number of examples in a dataset is a common need for doing machine learning where you generally need to partition a dataset into training, dev, and testing examples.
*Higgs Boson* dataset:
<https://archive.ics.uci.edu/ml/datasets/HIGGS> |
21,192,133 | Let's say I have a program that uses a .txt file to store data it needs to operate. Because it's a very large amount of data (just go with it) in the text file I was to use a generator rather than an iterator to go through the data in it so that my program leaves as much space as possible. Let's just say (I know this isn't secure) that it's a list of usernames. So my code would look like this (using python 3.3).
```
for x in range LenOfFile:
id = file.readlines(x)
if username == id:
validusername = True
#ask for a password
if validusername == True and validpassword == True:
pass
else:
print("Invalid Username")
```
Assume that valid password is set to True or False where I ask for a password. My question is, since I don't want to take up all of the RAM I don't want to use readlines() to get the whole thing, and with the code here I only take a very small amount of RAM at any given time. However, I am not sure how I would get the number of lines in the file (assume I cannot find the number of lines and add to it as new users arrive). Is there a way Python can do this without reading the entire file and storing it at once? I already tried `len()`, which apparently doesn't work on text files but was worth a try. The one way I have thought of to do this is not too great, it involves just using readlines one line at a time in a range so big the text file must be smaller, and then continuing when I get an error. I would prefer not to use this way, so any suggestions would be appreciated. | 2014/01/17 | [
"https://Stackoverflow.com/questions/21192133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2945577/"
] | Yes, the good news is you can find number of lines in a text file without readlines, for line in file, etc. More specifically in python you can use byte functions, random access, parallel operation, and regular expressions, instead of slow sequential text line processing. Parallel text file like CSV file line counter is particularly suitable for SSD devices which have fast random access, when combined with a many processor cores. I used a 16 core system with SSD to store the Higgs Boson dataset as a standard file which you can go download to test on. Even more specifically here are fragments from working code to get you started. You are welcome to freely copy and use but if you do then please cite my work thank you:
```
import re
from argparse import ArgumentParser
from multiprocessing import Pool
from itertools import repeat
from os import stat
unitTest = 0
fileName = None
balanceFactor = 2
numProcesses = 1
if __name__ == '__main__':
argparser = ArgumentParser(description='Parallel text file like CSV file line counter is particularly suitable for SSD which have fast random access')
argparser.add_argument('--unitTest', default=unitTest, type=int, required=False, help='0:False 1:True.')
argparser.add_argument('--fileName', default=fileName, required=False, help='')
argparser.add_argument('--balanceFactor', default=balanceFactor, type=int, required=False, help='integer: 1 or 2 or 3 are typical')
argparser.add_argument('--numProcesses', default=numProcesses, type=int, required=False, help='integer: 1 or more. Best when matched to number of physical CPU cores.')
cmd = vars(argparser.parse_args())
unitTest=cmd['unitTest']
fileName=cmd['fileName']
balanceFactor=cmd['balanceFactor']
numProcesses=cmd['numProcesses']
#Do arithmetic to divide partitions into startbyte, endbyte strips among workers (2 lists of int)
#Best number of strips to use is 2x to 3x number of workers, for workload balancing
#import numpy as np # long heavy import but i love numpy syntax
def PartitionDataToWorkers(workers, items, balanceFactor=2):
strips = balanceFactor * workers
step = int(round(float(items)/strips))
startPos = list(range(1, items+1, step))
if len(startPos) > strips:
startPos = startPos[:-1]
endPos = [x + step - 1 for x in startPos]
endPos[-1] = items
return startPos, endPos
def ReadFileSegment(startByte, endByte, fileName, searchChar='\n'): # counts number of searchChar appearing in the byte range
with open(fileName, 'r') as f:
f.seek(startByte-1) # seek is initially at byte 0 and then moves forward the specified amount, so seek(5) points at the 6th byte.
bytes = f.read(endByte - startByte + 1)
cnt = len(re.findall(searchChar, bytes)) # findall with implicit compiling runs just as fast here as re.compile once + re.finditer many times.
return cnt
if 0 == unitTest:
# Run app, not unit tests.
fileBytes = stat(fileName).st_size # Read quickly from OS how many bytes are in a text file
startByte, endByte = PartitionDataToWorkers(workers=numProcesses, items=fileBytes, balanceFactor=balanceFactor)
p = Pool(numProcesses)
partialSum = p.starmap(ReadFileSegment, zip(startByte, endByte, repeat(fileName))) # startByte is already a list. fileName is made into a same-length list of duplicates values.
globalSum = sum(partialSum)
print(globalSum)
else:
print("Running unit tests") # Bash commands like: head --bytes 96 beer.csv are how I found the correct values.
fileName='beer.csv' # byte 98 is a newline
assert(8==ReadFileSegment(1, 288, fileName))
assert(1==ReadFileSegment(1, 100, fileName))
assert(0==ReadFileSegment(1, 97, fileName))
assert(1==ReadFileSegment(97, 98, fileName))
assert(1==ReadFileSegment(98, 99, fileName))
assert(0==ReadFileSegment(99, 99, fileName))
assert(1==ReadFileSegment(98, 98, fileName))
assert(0==ReadFileSegment(97, 97, fileName))
print("OK")
```
The bash wc program is slightly faster but you wanted pure python, and so did I. Below is some performance testing results. That said if you change some of this code to use cython or something you might even get some more speed.
```
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000
real 0m2.257s
user 0m12.088s
sys 0m20.512s
HP-Z820:/mnt/fastssd/fast_file_reader$ time wc -l HIGGS.csv
11000000 HIGGS.csv
real 0m1.820s
user 0m0.364s
sys 0m1.456s
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000
real 0m2.256s
user 0m10.696s
sys 0m19.952s
HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=1 --balanceFactor=1
11000000
real 0m17.380s
user 0m11.124s
sys 0m6.272s
```
Conclusion: The speed is good for a pure python program compared to a C program. However, it’s not good enough to use the pure python program over the C program.
I wondered if compiling the regex just one time and passing it to all workers will improve speed. Answer: Regex pre-compiling does NOT help in this application. I suppose the reason is that the overhead of process serialization and creation for all the workers is dominating.
One more thing. Does parallel CSV file reading even help, I wondered? Is the disk the bottleneck, or is it the CPU? Oh yes, yes it does. Parallel file reading works quite well. Well there you go!
Data science is a typical use case for pure python. I like to use python (jupyter) notebooks, and I like to keep all code in the notebook rather than use bash scripts when possible. Finding the number of examples in a dataset is a common need for doing machine learning where you generally need to partition a dataset into training, dev, and testing examples.
*Higgs Boson* dataset:
<https://archive.ics.uci.edu/ml/datasets/HIGGS> | If you want number of lines in a file so badly, why don't you use `len`
```
with open("filename") as f:
num = len(f.readlines())
``` |
29,191,405 | I'm a little confused about when I need to explicitly copy an object in Python in order to make changes without altering the original. The [Python doc page](https://docs.python.org/3.4/library/copy.html) doesn't have too much detail, and simply says that "assignment statements do not create copies".
Example 1:
```
>>> a = 4
>>> b = a
>>> b += 1
>>> print(b)
>>> print(a)
# Results are what you'd "expect" them to be:
5
4
```
Example 2:
```
>>> class Test():
>>> def __init__(self, x):
>>> self.x = x
>>>
>>> A = Test(4)
>>> B = A
>>> B.x += 1
>>> print(B.x)
>>> print(A.x)
# Unexpected results because B isn't actually a copy of A:
5
5
```
Why do the two examples behave differently?
-------------------------------------------
Edit: In order to get Example 2 to work, I basically did the following. I'm asking why this isn't necessary for Example 1:
```
>>> import copy
>>> A = Test(4)
>>> B = copy.copy(A)
>>> B.x += 1
>>> print(B.x)
>>> print(A.x)
``` | 2015/03/22 | [
"https://Stackoverflow.com/questions/29191405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2856558/"
] | For starters, `(?<!...)` is **PCRE** in which the `perl = TRUE` parameter needs to be enabled.
The trick is to use lookahead here instead of lookbehind and add [**word boundaries**](http://www.rexegg.com/regex-boundaries.html#wordboundary) to force the regular expression engine to match whole words. Also, you broadly stated **words**; in my vocabulary this could mean any kind of word so I am going to use the Unicode property [`\pL`](http://www.regular-expressions.info/unicode.html), which matches any kind of letter from any language, if this matches more than expected you can simply change it back to `[a-zA-Z]` or use the POSIX named class `[[:alpha:]]` instead.
```
gsub("(?i)\\b(?!one)(\\pL+)\\b", "'\\1'", text, perl=T)
# [1] "one 'two' 'three' 'four' 'five' one 'six' one 'seven' one 'eight' 'nine' 'ten' one"
``` | You could try the below the PCRE regex
```
> gsub('\\bone\\b(*SKIP)(*F)|([A-Za-z]+)', "'\\1'", text, perl=TRUE)
[1] "one 'two' 'three' 'four' 'five' one 'six' one 'seven' one 'eight' 'nine' 'ten' one"
```
`\\bone\\b` matches the text `one` and the following `(*SKIP)(*F)` makes the match to skip and then fail. Now it uses the pattern which was on the right side of `|` operator to select characters from the remaining string (ie, except the skipped part)
[DEMO](https://regex101.com/r/lK9zP7/1) |
29,191,405 | I'm a little confused about when I need to explicitly copy an object in Python in order to make changes without altering the original. The [Python doc page](https://docs.python.org/3.4/library/copy.html) doesn't have too much detail, and simply says that "assignment statements do not create copies".
Example 1:
```
>>> a = 4
>>> b = a
>>> b += 1
>>> print(b)
>>> print(a)
# Results are what you'd "expect" them to be:
5
4
```
Example 2:
```
>>> class Test():
>>> def __init__(self, x):
>>> self.x = x
>>>
>>> A = Test(4)
>>> B = A
>>> B.x += 1
>>> print(B.x)
>>> print(A.x)
# Unexpected results because B isn't actually a copy of A:
5
5
```
Why do the two examples behave differently?
-------------------------------------------
Edit: In order to get Example 2 to work, I basically did the following. I'm asking why this isn't necessary for Example 1:
```
>>> import copy
>>> A = Test(4)
>>> B = copy.copy(A)
>>> B.x += 1
>>> print(B.x)
>>> print(A.x)
``` | 2015/03/22 | [
"https://Stackoverflow.com/questions/29191405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2856558/"
] | For starters, `(?<!...)` is **PCRE** in which the `perl = TRUE` parameter needs to be enabled.
The trick is to use lookahead here instead of lookbehind and add [**word boundaries**](http://www.rexegg.com/regex-boundaries.html#wordboundary) to force the regular expression engine to match whole words. Also, you broadly stated **words**; in my vocabulary this could mean any kind of word so I am going to use the Unicode property [`\pL`](http://www.regular-expressions.info/unicode.html), which matches any kind of letter from any language, if this matches more than expected you can simply change it back to `[a-zA-Z]` or use the POSIX named class `[[:alpha:]]` instead.
```
gsub("(?i)\\b(?!one)(\\pL+)\\b", "'\\1'", text, perl=T)
# [1] "one 'two' 'three' 'four' 'five' one 'six' one 'seven' one 'eight' 'nine' 'ten' one"
``` | Here's one way to do it in steps. First by quoting every word and then removing the quotes from the word you don't want quoted. It will probably solve what you need but may need some additional fine tuning for punctuation.
```
test <- paste0("'", text, "'")
test <- gsub(" ", "' '", test)
test <- gsub("'one'", "one", test)
``` |
29,191,405 | I'm a little confused about when I need to explicitly copy an object in Python in order to make changes without altering the original. The [Python doc page](https://docs.python.org/3.4/library/copy.html) doesn't have too much detail, and simply says that "assignment statements do not create copies".
Example 1:
```
>>> a = 4
>>> b = a
>>> b += 1
>>> print(b)
>>> print(a)
# Results are what you'd "expect" them to be:
5
4
```
Example 2:
```
>>> class Test():
>>> def __init__(self, x):
>>> self.x = x
>>>
>>> A = Test(4)
>>> B = A
>>> B.x += 1
>>> print(B.x)
>>> print(A.x)
# Unexpected results because B isn't actually a copy of A:
5
5
```
Why do the two examples behave differently?
-------------------------------------------
Edit: In order to get Example 2 to work, I basically did the following. I'm asking why this isn't necessary for Example 1:
```
>>> import copy
>>> A = Test(4)
>>> B = copy.copy(A)
>>> B.x += 1
>>> print(B.x)
>>> print(A.x)
``` | 2015/03/22 | [
"https://Stackoverflow.com/questions/29191405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2856558/"
] | For starters, `(?<!...)` is **PCRE** in which the `perl = TRUE` parameter needs to be enabled.
The trick is to use lookahead here instead of lookbehind and add [**word boundaries**](http://www.rexegg.com/regex-boundaries.html#wordboundary) to force the regular expression engine to match whole words. Also, you broadly stated **words**; in my vocabulary this could mean any kind of word so I am going to use the Unicode property [`\pL`](http://www.regular-expressions.info/unicode.html), which matches any kind of letter from any language, if this matches more than expected you can simply change it back to `[a-zA-Z]` or use the POSIX named class `[[:alpha:]]` instead.
```
gsub("(?i)\\b(?!one)(\\pL+)\\b", "'\\1'", text, perl=T)
# [1] "one 'two' 'three' 'four' 'five' one 'six' one 'seven' one 'eight' 'nine' 'ten' one"
``` | Seems like an odd thing to use regular expressions for. If you have more complicated expressions, perhaps something like this would work (and would be more readable).
```
# for piping and equals() and not()
library(magrittr)
#helper function
partialswap <- function(x, criteria, transform) {
idx<-criteria(x)
x[idx]<-transform(x[idx])
x
}
not_equals <- function(x) . %>% equals(x) %>% not
is_not_in <- function(x) . %>% is_in(x) %>% not
text <- "one two three four five one six one seven one eight nine ten one"
strsplit(text, " ")[[1]] %>%
partialswap(not_equals("one"), shQuote) %>%
paste(collapse=" ")
# [1] "one 'two' 'three' 'four' 'five' one 'six' one 'seven' one 'eight' 'nine' 'ten' one"
```
Or if you wanted to leave off "one" and "three"
```
strsplit(text, " ")[[1]] %>%
partialswap(is_not_in(c("one","three")), shQuote) %>%
paste(collapse=" ")
# [1] "one 'two' three 'four' 'five' one 'six' one 'seven' one 'eight' 'nine' 'ten' one"
``` |
68,199,583 | As you can see [here](https://i.stack.imgur.com/knIlJ.png), after I attempt to train my model in this cell, the asterisk disappears and the brackets are blank instead of containing a number. Do you know why this is happening, and how I can fix it? I'm running python 3.7 and TensorFlow 2.5.0. | 2021/06/30 | [
"https://Stackoverflow.com/questions/68199583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13004323/"
] | Unfortunately, that is indeed an **issue of Eclipse 2021-06 (4.20)** that happens inside conditions and loops when there is trailing code not separated by a semicolon `;` ([similar but not the same as in this question](https://stackoverflow.com/q/68258236/6505250)).
Example:
```
class Sample {
void sample(String foo) {
if (foo != null) {
sys // content assist here
System.out.println();
}
}
}
```
I created the [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) above and reported it here for you:
[**Eclipse bug 574267** - [content assist] [regression] No content assist for templates in conditional blocks](https://bugs.eclipse.org/bugs/show_bug.cgi?id=574267#c2)
As workaround you can add a `;` after the location where to use the content assist.
**Update:**
After less than 4 hours after [reporting a reproducible example](https://bugs.eclipse.org/bugs/show_bug.cgi?id=574267#c2), the [**issue has been fixed**](https://bugs.eclipse.org/bugs/show_bug.cgi?id=574267#c6). So, as an alternative to the above mentioned workaround, you can wait for the upcoming release **Eclipse 2021-09 (4.21)** on September 15, 2021 or at least for the first milestone build of it on July 16, 2021. | Could it be the same as [here](https://stackoverflow.com/a/68265945/6167720)?
(would have added comment, but too little rep) |
37,422,530 | Working my way through a beginners Python book and there's two fairly simple things I don't understand, and was hoping someone here might be able to help.
The example in the book uses regular expressions to take in email addresses and phone numbers from a clipboard and output them to the console. The code looks like this:
```
#! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard.
import pyperclip, re
# Create phone regex.
phoneRegex = re.compile(r'''(
(\d{3}|\(\d{3}\))? #[1] area code
(\s|-|\.)? #[2] separator
(\d{3}) #[3] first 3 digits
(\s|-|\.) #[4] separator
(\d{4}) #[5] last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #[6] extension
)''', re.VERBOSE)
# Create email regex.
emailRegex = re.compile(r'''(
[a-zA-Z0-9._%+-]+
@
[\.[a-zA-Z0-9.-]+
(\.[a-zA-Z]{2,4})
)''', re.VERBOSE)
# Find matches in clipboard text.
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
phoneNum = '-'.join([groups[1], groups[3], groups[5]])
if groups [8] != '':
phoneNum += ' x' + groups[8]
matches.append(phoneNum)
for groups in emailRegex.findall(text):
matches.append(groups[0])
# Copy results to the clipboard.
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Copied to Clipboard:')
print('\n'.join(matches))
else:
print('No phone numbers of email addresses found')
```
Okay, so firstly, I don't really understand the phoneRegex object. The book mentions that adding parentheses will create groups in the regular expression.
If that's the case, are my assumed index values in the comments wrong and should there really be two groups in the index marked one? Or if they're correct, what does groups[7,8] refer to in the matching loop below for phone numbers?
Secondly, why does the emailRegex use a mixture of lists and tuples, while the phoneRegex uses mainly tuples?
**Edit 1**
Thanks for the answers so far, they've been helpful. Still kind of confused on the first part though. Should there be eight indexes like rock321987's answer or nine like sweaver2112's one?
**Edit 2**
Answered, thank you. | 2016/05/24 | [
"https://Stackoverflow.com/questions/37422530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5195054/"
] | every opening left `(` marks the beginning of a capture group, and you can nest them:
```
( #[1] around whole pattern
(\d{3}|\(\d{3}\))? #[2] area code
(\s|-|\.)? #[3] separator
(\d{3}) #[4] first 3 digits
(\s|-|\.) #[5] separator
(\d{4}) #[6] last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #[7,8,9] extension
)
```
You should use [named groups](https://docs.python.org/2/howto/regex.html#non-capturing-and-named-groups) here `(?<groupname>pattern)`, along with clustering only parens `(?:pattern)` that don't capture anything. And remember, you should capture quantified constructs, not quantify captured constructs:
```
(?<areacode>(?:\d{3}|\(\d{3}\))?)
(?<separator>(?:\s|-|\.)?)
(?<exchange>\d{3})
(?<separator2>\s|-|\.)
(?<lastfour>\d{4})
(?<extension>(?:\s*(?:ext|x|ext.)\s*(?:\d{2,5}))?)
``` | ```
( #[1] around whole pattern
(\d{3}|\(\d{3}\))? #[2] area code
(\s|-|\.)? #[3] separator
(\d{3}) #[4] first 3 digits
(\s|-|\.) #[5] separator
(\d{4}) #[6] last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #[7] extension
<----------> <------->
^^ ^^
|| ||
[8] [9]
)
```
**Second Question**
You are understanding it entirely wrong. You are mixing python with regex.
In regex
>
> `[]` character class (and not list)
>
>
> `()` capturing group (and not tuple)
>
>
>
So whatever is inside these have nothing to do with `list` and `tuple` in python. Regex can be considered itself as a language and `()`, `[]` etc. are part of regex |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.