qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
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_pee...
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_pee...
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()) nbyte...
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...
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 ...
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 contai...
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 di...
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 D...
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 ...
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 f...
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 ...
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 ...
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.Sho...
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 simpl...
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: ...
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...
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 simpl...
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: ...
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 th...
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.co...
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...
### 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 o...
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 updat...
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 ...
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...
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 ...
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 care...
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 modific...
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 (pe...
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 ...
[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-...
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 (pe...
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 explana...
[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-...
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 te...
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 te...
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 te...
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.webdrive...
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]...
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 ...
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 ...
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.wiki...
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,...
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 ...
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,...
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 obje...
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 ...
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.wiki...
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 obje...
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,...
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,...
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,...
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 (tho...
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,...
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 pre...
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,...
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 (tho...
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,...
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 pre...
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 t...
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) @SpringBoot...
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(messagePaylo...
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...
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 Dat...
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/197...
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...
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 Dat...
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 @dat...
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...
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/197...
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 @dat...
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("di...
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...
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"); }...
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...
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...
> > **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, en...
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 nam...
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 nam...
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...
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...
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) ...
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...
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() ...
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...
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...
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) ...
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...
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...
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) ...
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() ...
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...
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) ...
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...
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() ...
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...
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: ``` br...
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...
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 ...
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 inst...
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...
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 thro...
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/quest...
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 actuall...
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/ li...
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/quest...
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 actuall...
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/quest...
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 actuall...
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](http...
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/quest...
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 actuall...
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...
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/quest...
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/ li...
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/quest...
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/ li...
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](http...
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/quest...
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/ li...
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...
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/quest...
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](http...
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/quest...
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...
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...
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 calcul...
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) ``...
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...
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 calcul...
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 lo...
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...
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) ``...
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...
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 lo...
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) ``...
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...
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 lo...
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...
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/cl...
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 `<...
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...
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 `<...
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...
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/cl...
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...
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+(?!\...
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. l...
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</proper...
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 resolve...
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 enviro...
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 ...
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 c...
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...
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 itsel...
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 initia...
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...
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 itsel...
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 ...
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...
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 initia...
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 ...
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</...
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 follo...
``` 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> ...
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</...
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 follo...
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> ... <artifac...
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</...
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 follo...
``` 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</...
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> ... <artifac...
``` 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> ...
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</...
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> ... <artifac...
``` 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.fromstr...
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.fromstr...
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.fromstr...
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.fromstr...
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.fromstr...
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...
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 ca...
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...
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...
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 ca...
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 i...
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...
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...
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 i...
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" secre...
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" >>...
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" ch...
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 simpl...
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 t...
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 test...
37,866,313
I did `ls -l /usr/bin/python` I got [![enter image description here](https://i.stack.imgur.com/wvA2p.png)](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 -> pyth...
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 b...
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(stri...
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?...
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...
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> ![ripple](https://i.stack.imgur.com/iIWa0.png...
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[:,...
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 twea...
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> ![ripple](https://i.stack.imgur.com/iIWa0.png...
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 twea...
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 alterna...
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> ![ripple](https://i.stack.imgur.com/iIWa0.png...
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 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 alterna...
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: ...
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 ...
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 interva...
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 i...
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 ...
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 i...
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 ...
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 i...
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 i...
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 i...
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: ``` >>...
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...
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...
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: ``` >>...
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...
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", t...
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: ``` >>...
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...
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...
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 ...
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 ...
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|-|\.) ...
``` ( #[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...