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
72,404,096
Trying to run examples or telegram bots from official site - <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples> Installed : ``` pip install python-telegram-bot ``` and when i run the example, i got error back that version is not compatible. ``` if __version_info__ < (20, 0, 0, "alpha"...
2022/05/27
[ "https://Stackoverflow.com/questions/72404096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14333315/" ]
Assuming you have only one non-NaN per row, you can `stack`: ```py df.stack().droplevel(1).to_frame(name='Fruits') ``` Output: ``` Fruits 0 Apple 1 Pear 2 Orange 3 Mango 4 banana ``` #### Handling rows with only NaNs: ```py df.stack().droplevel(1).to_frame(name='Fruits').reindex(df.index) ``` Outpu...
We can use a modification of an approach from [Transform Multiple Columns Into One With Pandas](https://stackoverflow.com/questions/47994917/transform-multiple-columns-into-one-with-pandas) to combine columns: ``` df['new'] = df.fillna('').sum(1) ``` **Explanation** * replace all nan values with an empty string * ...
72,404,096
Trying to run examples or telegram bots from official site - <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples> Installed : ``` pip install python-telegram-bot ``` and when i run the example, i got error back that version is not compatible. ``` if __version_info__ < (20, 0, 0, "alpha"...
2022/05/27
[ "https://Stackoverflow.com/questions/72404096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14333315/" ]
I would use [`bfill()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.bfill.html): ``` df = pd.DataFrame({ 'fruit_1': [None, 'Pear', None, None], 'fruit_2': ['Apple', None, None, None], 'fruit_3': [None, None, 'Orange', None]}) df.bfill(axis=1).iloc[:,0].rename('fruits') # returns ``` ...
We can use a modification of an approach from [Transform Multiple Columns Into One With Pandas](https://stackoverflow.com/questions/47994917/transform-multiple-columns-into-one-with-pandas) to combine columns: ``` df['new'] = df.fillna('').sum(1) ``` **Explanation** * replace all nan values with an empty string * ...
33,919,806
Is there a recommended way for using BeautifulSoup 4 in python when you have a table with no class or attribute values? I was considering just using Get\_Text() to dump the text out but if I wanted to pick individual values out or break the table into more discrete sections how would I go about it ? ```html <table ce...
2015/11/25
[ "https://Stackoverflow.com/questions/33919806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2645252/" ]
Let's look at your jQuery: ``` $('div#info.Data') // Gets <div> with id="info" and class="Data" // ^ You have id and class reversed! .eq(1) // This gets the 2nd element in the array // ^ You only tried to get 1 element. What is the 2nd? .text() // Returns co...
First of all, you have you're `id` and `class` the wrong way round but this is a simple fix. An alternative to your solution is to grab all the content, split it out into an array and then clean the empty strings caused by the new lines and `<br />` tags. This can then be used in any matter you like. ```js $(docume...
38,259,749
How can I split the a column into two separate ones. Would apply be the way to go about this? I want to keep the other columns in the DataFrame. For example I have a column called "last\_created" with a bunch of dates and times: "2016-07-01 09:50:09" I want to create two new columns "date" and "time" with the split v...
2016/07/08
[ "https://Stackoverflow.com/questions/38259749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5405782/" ]
`now()` is mysql function . In PHP we use **[time()](http://php.net/manual/en/function.time.php)** to get the current timestamp It is used as ``` $now = time();// get current timestamp ``` Use [**`strtotime()`**](http://php.net/manual/en/function.strtotime.php) to convert date in time stamp then use for comparison...
You are in right Direction, change it like ``` <?php //SELECT QUERY... foreach($events->results() as $e): $now = date("Y-m-d H:i:s"); if(date("Y-m-d H:i:s", strtotime($e->event_date)) >= $now){ echo "<h1>Show Event</h1>"; }else{ echo "<h1>DON'T Show Event</h1>"; ...
29,650,935
I am trying to convert a python game (made with pygame) into a exe file for windows, and I did using cx\_Freeze. No problems there. The thing is that when I launch myGame.exe, it opens the normal Pygame window and a console window(which I do not want). Is there a way to remove the console window? I read most of th...
2015/04/15
[ "https://Stackoverflow.com/questions/29650935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3580258/" ]
So what was wrong, was that the setup.py file was missing a parameter. What you need to add is `base = "Win32GUI"` to declare that you do not need a console window upon launch of the application. Here's the code: ``` import cx_Freeze exe = [cx_Freeze.Executable("myGame.py", base = "Win32GUI")] # <-- HERE cx_F...
The parameter can be passed also by the shell if you are making a quick executable like this: ``` cxfreeze my_program.py --base-name=WIN32GUI ```
16,797,850
I am trying to get gimp to use a reasonable default path in a "save as" plugin, and to do that I need to be able to specify the default with the return value of a function (I believe). Currently, my code is something like: ``` def do_the_foo(image, __unused_drawable, directory): # ... do something register( ...
2013/05/28
[ "https://Stackoverflow.com/questions/16797850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The fastest way would be to store the relevant data somewhere in a cache, and then print it, when you have time for it. Printing to the console is definitely slow, and using printf is maybe also not a good idea, especially if there are several variables to convert. Since I don't know the dynamics of your code, I can o...
You can switch buffering on by using C89's `setvbuf()`
64,964,188
Is there any simple way to swap character of string in python. In my case I want to swap `.` and `,` from `5.123.673,682`. So my string should become `5,123,673.682`. I have tried: ``` number = '5.123.673,682' number = number.replace('.', 'temp') number = number.replace(',', '.') number = number.replace('temp', ',') ...
2020/11/23
[ "https://Stackoverflow.com/questions/64964188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975806/" ]
One way using `dict.get`: ``` mapper = {".": ",", ",":"."} "".join([mapper.get(s, s) for s in '5.123.673,682']) ``` Or using `str.maketrans` and `str.translate`: ``` '5.123.673,682'.translate(str.maketrans(".,", ",.")) ``` Output: ``` '5,123,673.682' ```
This is a pythonic and clean approach to do that ```py def swap(c): if c == ',': return '.' elif c == '.': return ',' else: return c number = '5.123.673,682' new_number = ''.join(swap(o) for o in number) ```
64,964,188
Is there any simple way to swap character of string in python. In my case I want to swap `.` and `,` from `5.123.673,682`. So my string should become `5,123,673.682`. I have tried: ``` number = '5.123.673,682' number = number.replace('.', 'temp') number = number.replace(',', '.') number = number.replace('temp', ',') ...
2020/11/23
[ "https://Stackoverflow.com/questions/64964188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975806/" ]
One way using `dict.get`: ``` mapper = {".": ",", ",":"."} "".join([mapper.get(s, s) for s in '5.123.673,682']) ``` Or using `str.maketrans` and `str.translate`: ``` '5.123.673,682'.translate(str.maketrans(".,", ",.")) ``` Output: ``` '5,123,673.682' ```
If you only need to swap single characters, think of it as a mapping instead ``` def mapping(c): if c == ',': return '.' if c == '.': return ',' return c number = '5.123.673,682' converted = ''.join(map(mapping, number)) print(converted) ``` 5,123,673.682
72,317,862
``` Please here is my code def train_apparentflow_net(): code_path = config.code_dir fold = int(sys.argv[1]) print('fold = {}'.format(fold)) if fold == 0: mode_train = 'all' mode_val = 'all' elif fold in range(1,6): mode_train = 'train' mode_val = 'val' else: ...
2022/05/20
[ "https://Stackoverflow.com/questions/72317862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19131126/" ]
Please look at the following answer [sys.argv[1] description](https://stackoverflow.com/questions/4117530/sys-argv1-meaning-in-script) It is failing as there is no argument provided. You could try ``` fold = int(sys.argv[0]) ```
if all you need is to select the model, why not add the names in a list and select base on index like this ``` model_list = ["model_apparentflow_net_fold0_epoch050.h5", "model_apparentflow_net_fold1_epoch050.h5", "model_apparentflow_net_fold2_epoch050.h5", "model_apparentflow_net_fold3_epoch050.h5", "model_apparentf...
3,405,073
Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this: ``` mydict[key][subkey][subkey2]="value" ``` without having to check that mydict[key] etc. are actually set to be a dict, e.g. using ``` if not key in mydict: mydict[key]={} ``` The creation o...
2010/08/04
[ "https://Stackoverflow.com/questions/3405073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369113/" ]
``` class D(dict): def __missing__(self, key): self[key] = D() return self[key] d = D() d['a']['b']['c'] = 3 ```
You could use a tuple as the key for the dict and then you don't have to worry about subdictionaries at all: ``` mydict[(key,subkey,subkey2)] = "value" ``` Alternatively, if you really need to have subdictionaries for some reason you could use [`collections.defaultdict`](http://docs.python.org/library/collections.ht...
3,405,073
Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this: ``` mydict[key][subkey][subkey2]="value" ``` without having to check that mydict[key] etc. are actually set to be a dict, e.g. using ``` if not key in mydict: mydict[key]={} ``` The creation o...
2010/08/04
[ "https://Stackoverflow.com/questions/3405073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369113/" ]
You could use a tuple as the key for the dict and then you don't have to worry about subdictionaries at all: ``` mydict[(key,subkey,subkey2)] = "value" ``` Alternatively, if you really need to have subdictionaries for some reason you could use [`collections.defaultdict`](http://docs.python.org/library/collections.ht...
I like Dave's answer better, but here's an alternative. ``` from collections import defaultdict d = defaultdict(lambda : defaultdict(int)) >>> d['a']['b'] += 1 >>> d defaultdict(<function <lambda> at 0x652f0>, {'a': defaultdict(<type 'int'>, {'b': 1})}) >>> d['a']['b'] 1 ``` <http://tumble.philadams.net/post/852694...
3,405,073
Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this: ``` mydict[key][subkey][subkey2]="value" ``` without having to check that mydict[key] etc. are actually set to be a dict, e.g. using ``` if not key in mydict: mydict[key]={} ``` The creation o...
2010/08/04
[ "https://Stackoverflow.com/questions/3405073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369113/" ]
``` class D(dict): def __missing__(self, key): self[key] = D() return self[key] d = D() d['a']['b']['c'] = 3 ```
I like Dave's answer better, but here's an alternative. ``` from collections import defaultdict d = defaultdict(lambda : defaultdict(int)) >>> d['a']['b'] += 1 >>> d defaultdict(<function <lambda> at 0x652f0>, {'a': defaultdict(<type 'int'>, {'b': 1})}) >>> d['a']['b'] 1 ``` <http://tumble.philadams.net/post/852694...
61,590,884
my list looks like: ``` lst ['78251'], ['18261'], ['435921'], ['74252'], ...] ``` I want to place that numbers into a url code <http://api.brain-map.org/api/v2/data/query.xml?criteria=model::SectionDataSet,rma::criteria,[failed>$eq%27false%27],products[abbreviation$eq%27Mouse%27],genes[entrez\_id$eq%27**inhere**...
2020/05/04
[ "https://Stackoverflow.com/questions/61590884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9353795/" ]
The URL is complex, but see example URL: ``` a= 'http://api.brain-map.org/api/v2/data/query.xml?criteria=' + i + '&gene=model:' + i ```
Try this much more pythonic approach, using .format(): ``` for i in lst: b = "http://api.brain-map.org/api/v2/data/query.xml?criteria=model::SectionDataSet,rma::criteria,[failed$eq%27false%27],products[abbreviation$eq%27Mouse%27],genes[entrez_id$eq%27{}%27]".format(i[0]) ```
61,590,884
my list looks like: ``` lst ['78251'], ['18261'], ['435921'], ['74252'], ...] ``` I want to place that numbers into a url code <http://api.brain-map.org/api/v2/data/query.xml?criteria=model::SectionDataSet,rma::criteria,[failed>$eq%27false%27],products[abbreviation$eq%27Mouse%27],genes[entrez\_id$eq%27**inhere**...
2020/05/04
[ "https://Stackoverflow.com/questions/61590884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9353795/" ]
The URL is complex, but see example URL: ``` a= 'http://api.brain-map.org/api/v2/data/query.xml?criteria=' + i + '&gene=model:' + i ```
``` lst = [["78251"], ["18261"], ["435921"], ["74252"]] for val, in lst: b = "http://api.brain-map.org/api/v2/data/query.xml?criteria=model::SectionDataSet," \ "rma::criteria,[failed$eq%27false%27],products[abbreviation$eq%27Mouse%27]," \ f"genes[entrez_id$eq%27{val}%27]" ``` Directly access to va...
61,590,884
my list looks like: ``` lst ['78251'], ['18261'], ['435921'], ['74252'], ...] ``` I want to place that numbers into a url code <http://api.brain-map.org/api/v2/data/query.xml?criteria=model::SectionDataSet,rma::criteria,[failed>$eq%27false%27],products[abbreviation$eq%27Mouse%27],genes[entrez\_id$eq%27**inhere**...
2020/05/04
[ "https://Stackoverflow.com/questions/61590884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9353795/" ]
Try this much more pythonic approach, using .format(): ``` for i in lst: b = "http://api.brain-map.org/api/v2/data/query.xml?criteria=model::SectionDataSet,rma::criteria,[failed$eq%27false%27],products[abbreviation$eq%27Mouse%27],genes[entrez_id$eq%27{}%27]".format(i[0]) ```
``` lst = [["78251"], ["18261"], ["435921"], ["74252"]] for val, in lst: b = "http://api.brain-map.org/api/v2/data/query.xml?criteria=model::SectionDataSet," \ "rma::criteria,[failed$eq%27false%27],products[abbreviation$eq%27Mouse%27]," \ f"genes[entrez_id$eq%27{val}%27]" ``` Directly access to va...
41,254,635
Basically I'm just starting out with python networking and python in general and I can't get my TCP client to send data. It says: ``` Traceback (most recent call last): File "script.py", line 14, in <module> client.send(data) #this is where I get the error TypeError: a bytes-like object is required, not 'str' `...
2016/12/21
[ "https://Stackoverflow.com/questions/41254635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7323709/" ]
You are probably using Python 3.X. [`socket.send()`](https://docs.python.org/3.5/library/socket.html#socket.socket.send) expected a bytes type argument but `data` is an unicode string. You must encode the string using [`str.encode()`](https://docs.python.org/3/library/stdtypes.html#str.encode) method. Similarly you wou...
If you are using python2.x your code is correct. As in the documentation for python2 [`socket.send()`](https://docs.python.org/2/library/socket.html#socket.socket.send) takes a string parameter. But if you are using python3.x you can see that [`socket.send()`](https://docs.python.org/3.6/library/socket.html#socket.sock...
41,254,635
Basically I'm just starting out with python networking and python in general and I can't get my TCP client to send data. It says: ``` Traceback (most recent call last): File "script.py", line 14, in <module> client.send(data) #this is where I get the error TypeError: a bytes-like object is required, not 'str' `...
2016/12/21
[ "https://Stackoverflow.com/questions/41254635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7323709/" ]
You are probably using Python 3.X. [`socket.send()`](https://docs.python.org/3.5/library/socket.html#socket.socket.send) expected a bytes type argument but `data` is an unicode string. You must encode the string using [`str.encode()`](https://docs.python.org/3/library/stdtypes.html#str.encode) method. Similarly you wou...
So I encoded the data with utf-8 as was suggested by a few people and rewrote my code which fixed the odd syntax error. Now my code works perfectly. Thank you to everyone who posted but especially to @FJSevilla. The working code is as follows: ``` import socket target_host = "www.google.com" target_port = 80 client ...
41,254,635
Basically I'm just starting out with python networking and python in general and I can't get my TCP client to send data. It says: ``` Traceback (most recent call last): File "script.py", line 14, in <module> client.send(data) #this is where I get the error TypeError: a bytes-like object is required, not 'str' `...
2016/12/21
[ "https://Stackoverflow.com/questions/41254635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7323709/" ]
You are probably using Python 3.X. [`socket.send()`](https://docs.python.org/3.5/library/socket.html#socket.socket.send) expected a bytes type argument but `data` is an unicode string. You must encode the string using [`str.encode()`](https://docs.python.org/3/library/stdtypes.html#str.encode) method. Similarly you wou...
Another suggestion using Python 3.7 is to add the letter "b" in the message. For example: ``` s.send(b"GET / HTTP/1.1\r\nHost: google.com\r\n\r\n") ``` ``` import socket t_host = "www.google.com" t_port = 80 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((t_host, t_port)) s.send(b"GET / HTTP/1.1...
3,246,021
I am posting to Hudson server using curl from the command line using the following-- ``` curl -X POST -d '<run><log encoding="hexBinary">4142430A</log><result>0</result><duration>2000</duration></run>' \ http://user:pass@myhost/hudson/job/_jobName_/postBuildResult ``` as shown in the hudson documentation..can I emu...
2010/07/14
[ "https://Stackoverflow.com/questions/3246021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361179/" ]
``` import urllib2 req = urllib2.Request(url, data) response = urllib2.urlopen(req) result = response.read() ``` where data is the encoded data you want to POST. You can encode a dict using urllib like this: ``` import urllib values = { 'foo': 'bar' } data = urllib.urlencode(values) ```
The modern day solution to this is much simpler with the [requests](http://docs.python-requests.org/) module (tagline: *HTTP for humans!* :) ``` import requests r = requests.post('http://httpbin.org/post', data = {'key':'value'}, auth=('user', 'passwd')) r.text # response as a string r.content # response as a ...
7,149,137
Within a python program I need to run a command in background, without displaying its output. Therefore I'm doing `os.system("nohup " + command + " &")` for now. Edit : `command` shouldn't be killed/closed when python program exits. However that will only work on Linux, and the content of the file will end up in `noh...
2011/08/22
[ "https://Stackoverflow.com/questions/7149137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692562/" ]
You are looking for a daemon process. Look at [How do you create a daemon in Python?](https://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python) or <http://blog.ianbicking.org/daemon-best-practices.html>
Look into the [subprocess](http://docs.python.org/library/subprocess.html) module. ``` from subprocess import Popen, PIPE process = Popen(['command', 'arg'], stdout=PIPE) ```
22,084,046
Python 2.7.5 I added the homebrew/science to my brew taps. I ran ``` brew install opencv. ``` bash profile I added ``` export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH ``` I've opened the headgazer folder and run ``` python tracker.py Traceback (most recent call last): File "tracker.py",...
2014/02/28
[ "https://Stackoverflow.com/questions/22084046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172232/" ]
Very straightforward with `awk`: ``` $ cat file 1 2 3 4 5 6 ``` ``` $ awk 'NR==3{print "hello\n"}1' file 1 2 hello 3 4 5 6 ``` Where `NR` is the line number. You can set it to any number you wish to insert text to.
Does it have to be sed? ``` head -2 infile ; echo Hello ; echo ; tail +3 infile ```
22,084,046
Python 2.7.5 I added the homebrew/science to my brew taps. I ran ``` brew install opencv. ``` bash profile I added ``` export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH ``` I've opened the headgazer folder and run ``` python tracker.py Traceback (most recent call last): File "tracker.py",...
2014/02/28
[ "https://Stackoverflow.com/questions/22084046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172232/" ]
Does it have to be sed? ``` head -2 infile ; echo Hello ; echo ; tail +3 infile ```
``` sed '3 i\ Hello\ ' YopurFile ``` Insert following line (preceded by `\`) at line 3
22,084,046
Python 2.7.5 I added the homebrew/science to my brew taps. I ran ``` brew install opencv. ``` bash profile I added ``` export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH ``` I've opened the headgazer folder and run ``` python tracker.py Traceback (most recent call last): File "tracker.py",...
2014/02/28
[ "https://Stackoverflow.com/questions/22084046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172232/" ]
Very straightforward with `awk`: ``` $ cat file 1 2 3 4 5 6 ``` ``` $ awk 'NR==3{print "hello\n"}1' file 1 2 hello 3 4 5 6 ``` Where `NR` is the line number. You can set it to any number you wish to insert text to.
``` $ sed '3s/^/Hello\n\n/' file.txt 1st 2nd Hello 3rd ``` The `3` at the beginning of the `sed` command specifies that the command should be applied to line 3 only. Thus, the command, `3s/^/Hello\n\n/`, substitutes in "Hello" and two new lines to the beginning (`^` matches the beginning of a line) of line 3. Otherw...
22,084,046
Python 2.7.5 I added the homebrew/science to my brew taps. I ran ``` brew install opencv. ``` bash profile I added ``` export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH ``` I've opened the headgazer folder and run ``` python tracker.py Traceback (most recent call last): File "tracker.py",...
2014/02/28
[ "https://Stackoverflow.com/questions/22084046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172232/" ]
``` $ sed '3s/^/Hello\n\n/' file.txt 1st 2nd Hello 3rd ``` The `3` at the beginning of the `sed` command specifies that the command should be applied to line 3 only. Thus, the command, `3s/^/Hello\n\n/`, substitutes in "Hello" and two new lines to the beginning (`^` matches the beginning of a line) of line 3. Otherw...
``` sed '3 i\ Hello\ ' YopurFile ``` Insert following line (preceded by `\`) at line 3
22,084,046
Python 2.7.5 I added the homebrew/science to my brew taps. I ran ``` brew install opencv. ``` bash profile I added ``` export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH ``` I've opened the headgazer folder and run ``` python tracker.py Traceback (most recent call last): File "tracker.py",...
2014/02/28
[ "https://Stackoverflow.com/questions/22084046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172232/" ]
Very straightforward with `awk`: ``` $ cat file 1 2 3 4 5 6 ``` ``` $ awk 'NR==3{print "hello\n"}1' file 1 2 hello 3 4 5 6 ``` Where `NR` is the line number. You can set it to any number you wish to insert text to.
``` sed '3 i\ Hello\ ' YopurFile ``` Insert following line (preceded by `\`) at line 3
61,453,511
I have my flask app which would serve my flutter app using HTTP requests. Everything is okay when the mobile phone is connected to the PC. But once after we deploy the app to the mobile phone and detach it from the PC, how would the flask app serve the flutter app? Is there any way which would start the python script ...
2020/04/27
[ "https://Stackoverflow.com/questions/61453511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11170382/" ]
for testing purpose you can use ngrok to deploy your flask server, for more info [ngrok](https://ngrok.com/docs)
Your phone when connected to the PC is accessing a Flask app via 'localhost'. You have two options to make it work (i.e. access Flask based REST APIs from the mobile when not connected to the PC). 1. Expose Flask app to the network. And make sure both PC and the mobile phone are on the same wifi. [This](https://stacko...
14,970,952
Im kinda new to python, and dont really understand my issue, really appreciate the help. Anyways, this is the line of coding. ``` def Banker(warrior): gold = open(chairs[warrior-1], "strength") return gold ``` This is the error i got. ``` line 22, in Banker gold = open(chairs[warrior-1], "strength") Typ...
2013/02/20
[ "https://Stackoverflow.com/questions/14970952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089394/" ]
On a UNIX machine, use the [`pwent`](http://www.kernel.org/doc/man-pages/online/pages/man3/getpwent.3.html) series of functions: ``` #include <sys/types.h> #include <pwd.h> int main() { struct passwd *p; while((p = getpwent())) { printf("name: %s\n", p->pw_name); } } ``` This will consult the sy...
The users of a machine are listed in /etc/passwd. A good way to filter all 'human' users is to do ``` cat /etc/passwd | grep "/home" |cut -d: -f1 ``` as the human users usually have a home directory. Now, for calling it inside C, you may use popen. Take a look at ``` man popen ```
14,970,952
Im kinda new to python, and dont really understand my issue, really appreciate the help. Anyways, this is the line of coding. ``` def Banker(warrior): gold = open(chairs[warrior-1], "strength") return gold ``` This is the error i got. ``` line 22, in Banker gold = open(chairs[warrior-1], "strength") Typ...
2013/02/20
[ "https://Stackoverflow.com/questions/14970952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089394/" ]
The users of a machine are listed in /etc/passwd. A good way to filter all 'human' users is to do ``` cat /etc/passwd | grep "/home" |cut -d: -f1 ``` as the human users usually have a home directory. Now, for calling it inside C, you may use popen. Take a look at ``` man popen ```
tested on BSD. ``` #include <sys/types.h> #include <pwd.h> #include <stdio.h> int main(int argc, char** argv) { struct passwd *pwd; while((pwd = getpwent())!=NULL) { printf("%s\n",pwd->pw_name); } return 0; } ```
14,970,952
Im kinda new to python, and dont really understand my issue, really appreciate the help. Anyways, this is the line of coding. ``` def Banker(warrior): gold = open(chairs[warrior-1], "strength") return gold ``` This is the error i got. ``` line 22, in Banker gold = open(chairs[warrior-1], "strength") Typ...
2013/02/20
[ "https://Stackoverflow.com/questions/14970952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089394/" ]
On a UNIX machine, use the [`pwent`](http://www.kernel.org/doc/man-pages/online/pages/man3/getpwent.3.html) series of functions: ``` #include <sys/types.h> #include <pwd.h> int main() { struct passwd *p; while((p = getpwent())) { printf("name: %s\n", p->pw_name); } } ``` This will consult the sy...
``` #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <pwd.h> int main(int argc, char ** argv) { // You can restrict the range of UIDs // depending on whether you care about system users or real users int minUID = 0; int maxUID = 10000; for (int i = minUID; i < maxUID; ++i) ...
14,970,952
Im kinda new to python, and dont really understand my issue, really appreciate the help. Anyways, this is the line of coding. ``` def Banker(warrior): gold = open(chairs[warrior-1], "strength") return gold ``` This is the error i got. ``` line 22, in Banker gold = open(chairs[warrior-1], "strength") Typ...
2013/02/20
[ "https://Stackoverflow.com/questions/14970952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089394/" ]
``` #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <pwd.h> int main(int argc, char ** argv) { // You can restrict the range of UIDs // depending on whether you care about system users or real users int minUID = 0; int maxUID = 10000; for (int i = minUID; i < maxUID; ++i) ...
tested on BSD. ``` #include <sys/types.h> #include <pwd.h> #include <stdio.h> int main(int argc, char** argv) { struct passwd *pwd; while((pwd = getpwent())!=NULL) { printf("%s\n",pwd->pw_name); } return 0; } ```
14,970,952
Im kinda new to python, and dont really understand my issue, really appreciate the help. Anyways, this is the line of coding. ``` def Banker(warrior): gold = open(chairs[warrior-1], "strength") return gold ``` This is the error i got. ``` line 22, in Banker gold = open(chairs[warrior-1], "strength") Typ...
2013/02/20
[ "https://Stackoverflow.com/questions/14970952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089394/" ]
On a UNIX machine, use the [`pwent`](http://www.kernel.org/doc/man-pages/online/pages/man3/getpwent.3.html) series of functions: ``` #include <sys/types.h> #include <pwd.h> int main() { struct passwd *p; while((p = getpwent())) { printf("name: %s\n", p->pw_name); } } ``` This will consult the sy...
tested on BSD. ``` #include <sys/types.h> #include <pwd.h> #include <stdio.h> int main(int argc, char** argv) { struct passwd *pwd; while((pwd = getpwent())!=NULL) { printf("%s\n",pwd->pw_name); } return 0; } ```
74,618,168
I have just starting learning python and as I creating this program, which asks user to input two numbers, which then adds them to together using a simple `if-elif-else` statement, however the else part of the code just seems to not work if, an user types out the six, for example, in words instead of the number. ``` ...
2022/11/29
[ "https://Stackoverflow.com/questions/74618168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17851996/" ]
This should be what you are looking for: ``` try: num_1 = int(input("Enter the first number: ")) num_2 = int(input("Enter the second number: ")) except ValueError: print("invalid") exit() Total = num_1 + num_2 print("The total is: ", Total) if num_1 > num_2: print("num_1 is greater then num_2") elif...
In your first two lines you’re calling int() on a string in the situation you’re describing. This won’t work, and your code will stop running here. What you want is probably something call a try-catch statement.
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
Here's an [image](https://hub.docker.com/r/chennavarri/ubuntu_opencv_python/) that is built on Ubuntu 16.04 with Python2 + Python3 + OpenCV. You can pull it using `docker pull chennavarri/ubuntu_opencv_python` Here's the Dockerfile (provided in the same dockerhub repo mentioned above) that will install opencv for both...
if you want to use Opencv dnn with CUDA, and torch with gpu (optionally) i recommend this: ``` FROM nvidia/cuda:10.2-base-ubuntu18.04 WORKDIR /home ENV DEBIAN_FRONTEND=noninteractive ENV TZ=Europe/Minsk RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN apt-get update && apt-get inst...
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
Thanks for posting this. I ran into the same issue and tried your solution and although it seemed to install OpenCV it left me with an issue of conflicting versions of the Python six library so I took a different route. I think a simpler way to do this is to install Anaconda in your container and then add OpenCV. I'm u...
To install Opencv (latest) in docker ... the steps are similar to Linux version just the symlink path is different: ``` apt install -y libtiff5-dev libjpeg8-dev libpng-dev cmake make apt install -y libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev apt install -y libxine2-dev libv4l-dev apt install -y libg...
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
For some applications (as in my case) you can get away with using the python package **opencv-python-headless**. This will work directly within the docker image if all you are doing is CPU based opencv activities. ``` WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt C...
I use this Dockerfile and it works like a charm ``` FROM python:3.9 LABEL mantainer="Baher Elnaggar <eng.baher77@gmail.com>" WORKDIR /opt/build ENV OPENCV_VERSION="4.5.1" RUN apt-get -qq update \ && apt-get -qq install -y --no-install-recommends \ build-essential \ cmake \ git \ ...
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
Thanks for posting this. I ran into the same issue and tried your solution and although it seemed to install OpenCV it left me with an issue of conflicting versions of the Python six library so I took a different route. I think a simpler way to do this is to install Anaconda in your container and then add OpenCV. I'm u...
I use this Dockerfile and it works like a charm ``` FROM python:3.9 LABEL mantainer="Baher Elnaggar <eng.baher77@gmail.com>" WORKDIR /opt/build ENV OPENCV_VERSION="4.5.1" RUN apt-get -qq update \ && apt-get -qq install -y --no-install-recommends \ build-essential \ cmake \ git \ ...
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
Here's an [image](https://hub.docker.com/r/chennavarri/ubuntu_opencv_python/) that is built on Ubuntu 16.04 with Python2 + Python3 + OpenCV. You can pull it using `docker pull chennavarri/ubuntu_opencv_python` Here's the Dockerfile (provided in the same dockerhub repo mentioned above) that will install opencv for both...
I use this Dockerfile and it works like a charm ``` FROM python:3.9 LABEL mantainer="Baher Elnaggar <eng.baher77@gmail.com>" WORKDIR /opt/build ENV OPENCV_VERSION="4.5.1" RUN apt-get -qq update \ && apt-get -qq install -y --no-install-recommends \ build-essential \ cmake \ git \ ...
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
Fixed with a slightly different set-up ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # Various Python and C/build deps RUN apt-get update && apt-get install -y \ wget \ build-essential \ cmake \ git \ unzip \ pkg-con...
if you want to use Opencv dnn with CUDA, and torch with gpu (optionally) i recommend this: ``` FROM nvidia/cuda:10.2-base-ubuntu18.04 WORKDIR /home ENV DEBIAN_FRONTEND=noninteractive ENV TZ=Europe/Minsk RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN apt-get update && apt-get inst...
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
``` from ubuntu:12.10 # Ubuntu sides with libav, I side with ffmpeg. run echo "deb http://ppa.launchpad.net/jon-severinsson/ffmpeg/ubuntu quantal main" >> /etc/apt/sources.list run apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1DB8ADC1CFCA9579 run apt-get update run apt-get install -y -q wget curl run a...
I use this Dockerfile and it works like a charm ``` FROM python:3.9 LABEL mantainer="Baher Elnaggar <eng.baher77@gmail.com>" WORKDIR /opt/build ENV OPENCV_VERSION="4.5.1" RUN apt-get -qq update \ && apt-get -qq install -y --no-install-recommends \ build-essential \ cmake \ git \ ...
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
Thanks for posting this. I ran into the same issue and tried your solution and although it seemed to install OpenCV it left me with an issue of conflicting versions of the Python six library so I took a different route. I think a simpler way to do this is to install Anaconda in your container and then add OpenCV. I'm u...
``` from ubuntu:12.10 # Ubuntu sides with libav, I side with ffmpeg. run echo "deb http://ppa.launchpad.net/jon-severinsson/ffmpeg/ubuntu quantal main" >> /etc/apt/sources.list run apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1DB8ADC1CFCA9579 run apt-get update run apt-get install -y -q wget curl run a...
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
Fixed with a slightly different set-up ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # Various Python and C/build deps RUN apt-get update && apt-get install -y \ wget \ build-essential \ cmake \ git \ unzip \ pkg-con...
Thanks for posting this. I ran into the same issue and tried your solution and although it seemed to install OpenCV it left me with an issue of conflicting versions of the Python six library so I took a different route. I think a simpler way to do this is to install Anaconda in your container and then add OpenCV. I'm u...
36,862,589
I'm attempting to Dockerise a Python application, which depends on OpenCV. I've tried several different ways, but I keep getting... `ImportError: No module named cv2` when I attempt to run the application. Here's my current Dockerfile. ``` FROM python:2.7 MAINTAINER Ewan Valentine <ewan@theladbible.com> RUN mkdir ...
2016/04/26
[ "https://Stackoverflow.com/questions/36862589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541609/" ]
Here's an [image](https://hub.docker.com/r/chennavarri/ubuntu_opencv_python/) that is built on Ubuntu 16.04 with Python2 + Python3 + OpenCV. You can pull it using `docker pull chennavarri/ubuntu_opencv_python` Here's the Dockerfile (provided in the same dockerhub repo mentioned above) that will install opencv for both...
``` from ubuntu:12.10 # Ubuntu sides with libav, I side with ffmpeg. run echo "deb http://ppa.launchpad.net/jon-severinsson/ffmpeg/ubuntu quantal main" >> /etc/apt/sources.list run apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1DB8ADC1CFCA9579 run apt-get update run apt-get install -y -q wget curl run a...
49,768,187
When doing some simple calculation from dataframe object (python 3.5, pandas 0.20.1), pandas is not behaving consistently when the calculated result doesn't fit the current numeric type. Why? Please see code below, creating a dataframe with numeric type-int16 : ``` import pandas as pd import numpy as np d = {'col1':...
2018/04/11
[ "https://Stackoverflow.com/questions/49768187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6217667/" ]
You have to apply the :hover effect in a:hover because you have already applied background-color to a element. Try and add this code. ``` .tabs-nav a:hover { background-color: red; } ```
Below code works for me ``` .tabs-nav li :hover { color: white; background: red; } ``` If I am not wrong Space is added to apply hover to the child of li. In this case for anchor tag
49,768,187
When doing some simple calculation from dataframe object (python 3.5, pandas 0.20.1), pandas is not behaving consistently when the calculated result doesn't fit the current numeric type. Why? Please see code below, creating a dataframe with numeric type-int16 : ``` import pandas as pd import numpy as np d = {'col1':...
2018/04/11
[ "https://Stackoverflow.com/questions/49768187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6217667/" ]
You have to apply the :hover effect in a:hover because you have already applied background-color to a element. Try and add this code. ``` .tabs-nav a:hover { background-color: red; } ```
Nothing wrong with the `css` ,Here you applied `background` for `a` tag. So change the hover to `a` ``` .tabs-nav li:hover a { color: white; background: red; } ```
49,768,187
When doing some simple calculation from dataframe object (python 3.5, pandas 0.20.1), pandas is not behaving consistently when the calculated result doesn't fit the current numeric type. Why? Please see code below, creating a dataframe with numeric type-int16 : ``` import pandas as pd import numpy as np d = {'col1':...
2018/04/11
[ "https://Stackoverflow.com/questions/49768187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6217667/" ]
Nothing wrong with the `css` ,Here you applied `background` for `a` tag. So change the hover to `a` ``` .tabs-nav li:hover a { color: white; background: red; } ```
Below code works for me ``` .tabs-nav li :hover { color: white; background: red; } ``` If I am not wrong Space is added to apply hover to the child of li. In this case for anchor tag
46,247,732
So I am learning python and am trying to count the number of vowels in a sentence. I figured out how to do it both using the count() function and an iteration but now I am trying to do it using recursion. When I try the following method I get an error "IndexError: string index out of range". Here is my code. ``` sente...
2017/09/15
[ "https://Stackoverflow.com/questions/46247732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8616651/" ]
You have no base case. The function will keep recursing until `sentence` is empty, in which case your first if statement will cause that index error. You should first of all check if sentence is empty, and if so return 0
You can shorten things up quite a bit: ``` def count_vowels_recursive(sentence): # this base case is needed to stop the recursion if not sentence: return 0 # otherwise, sentence[0] will raise an exception for the empty string return (sentence[0] in "aeiou") + count_vowels_recursive(sentence[1...
46,247,732
So I am learning python and am trying to count the number of vowels in a sentence. I figured out how to do it both using the count() function and an iteration but now I am trying to do it using recursion. When I try the following method I get an error "IndexError: string index out of range". Here is my code. ``` sente...
2017/09/15
[ "https://Stackoverflow.com/questions/46247732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8616651/" ]
You have no base case. The function will keep recursing until `sentence` is empty, in which case your first if statement will cause that index error. You should first of all check if sentence is empty, and if so return 0
You can try this: ``` def count_vowels_recursive(s, count): if not s: return count else: new_count = count if s[0] in ["a", "e", "i", "o", "u"]: new_count += 1 return count_vowels_recursive(s[1:], new_count) ```
49,490,803
I'm working through a python workbook, and I have to turn the following dictionary into a list: ``` lexicon = { 'north': 'direction', 'south': 'direction', 'east': 'direction', 'west': 'direction', 'down': 'direction', 'up': 'direction', 'left': 'direction', 'right': 'direction', 'b...
2018/03/26
[ "https://Stackoverflow.com/questions/49490803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9429075/" ]
You can use `.keys()` or `.values()`. ``` >>> list(lexicon.keys()) ['princess', 'down', 'east', 'north', 'cabinet', 'at', 'right', 'door', 'left', 'up', 'from', 'bear', 'of', 'the', 'south', 'in', 'kill', 'eat', 'back', 'west', 'it', 'go', 'stop'] >>> list(lexicon.values()) ['noun', 'direction', 'direction', 'directio...
if you just want values you can use : `lexicon.values()` it will return you the values saved against each key. but if you want to have a list of key value pairs then you can use the following : ``` >>lexicon.items() output : [('right', 'direction'), ('it', 'stop'), ('down', 'direction'), ('kill', 'verb'), ('at...
38,471,306
As what I have understand on python, when you pass a variable on a function parameter it is already reference to the original variable. On my implementation when I try to equate a variable that I pass on the function it resulted empty list. This is my code: ``` #on the main ------------- temp_obj = [] obj = [ {'n...
2016/07/20
[ "https://Stackoverflow.com/questions/38471306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6099766/" ]
If all you want to do is switch from design view to code view then use the F7 key. In older versions of VS, F7 would switch back again too but in later versions you use Shift+F7 to switch from code view to design view. When in design view, you can select the form or a control/component, open the Properties window, cli...
Already resolved. I was able to do it by creating another project and choosing the windows form application as visual basic, not c#.
69,528,110
I have the following code ``` name = "testyaml" version = "2.5" os = "Linux" sources = [ { 'source': 'news', 'target': 'industry' }, { 'source': 'testing', 'target': 'computer' } ] ``` And I want to make this yaml with python3 ``` services: name: nam...
2021/10/11
[ "https://Stackoverflow.com/questions/69528110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/878280/" ]
```py import yaml name = "testyaml" version = "2.5" os = "Linux" sources = [ {"source": "news", "target": "industry"}, {"source": "testing", "target": "computer"}, ] yaml.dump( {"services": {"name": name, "version": version, "os": os, "sources": sources}} ) ```
Python's `yaml` module allows you to dump dictionary data into yaml format: ```py import yaml # Create a dictionary with your data tmp_data = dict( services=dict( name=name, version=version, os=os, sources=sources ) ) if __name__ == '__main__': with open('my_yaml.yaml', 'w...
26,810,892
I am trying to write the output of a python code in an excel sheet. Here's my attempt: ``` import xlwt wbk = xlwt.Workbook() sheet = wbk.add_sheet('pyt') row =0 # row counter col=0 # col counter inputdata = [(1,2,3,4),(2,3,4,5)] for c in inputdata: for d in c: sheet.write(row,col,d) col +=1 ...
2014/11/07
[ "https://Stackoverflow.com/questions/26810892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274879/" ]
You're seeing that behaviour because you're not setting `col` back to zero at the end of the row. Instead, though, you should use the built-in [`enumerate()`](https://docs.python.org/2/library/functions.html#enumerate) which handles the incrementing for you. ``` for row, c in enumerate(inputdata): for col, d in ...
Add `col = 0` on the next line after `row+=1`
1,650,095
I am reading the book [Think Python](http://www.greenteapress.com/thinkpython/) by Allen Downey. For chapter 4, one has to use a suite of modules called [Swampy](http://www.greenteapress.com/thinkpython/swampy/). I have downloaded and installed it. The problem is that the modules were written in Python 2 and I have Py...
2009/10/30
[ "https://Stackoverflow.com/questions/1650095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115139/" ]
Many important third-party libraries have not yet been rewritten for Python 3; you'll have to stick to Python 2.x for now. There is no way around it. As it says on the [official Python download page](http://www.python.org/download/), > > If you don't know which version to > use, start with Python 2.6.4; more > exis...
There is a conversion tool for converting Python 2 code to work with Python 3: <http://svn.python.org/view/sandbox/trunk/2to3/> Not sure how this extends to 3rd party libraries but it might be worth passing this over the swampy code.
1,650,095
I am reading the book [Think Python](http://www.greenteapress.com/thinkpython/) by Allen Downey. For chapter 4, one has to use a suite of modules called [Swampy](http://www.greenteapress.com/thinkpython/swampy/). I have downloaded and installed it. The problem is that the modules were written in Python 2 and I have Py...
2009/10/30
[ "https://Stackoverflow.com/questions/1650095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115139/" ]
Many important third-party libraries have not yet been rewritten for Python 3; you'll have to stick to Python 2.x for now. There is no way around it. As it says on the [official Python download page](http://www.python.org/download/), > > If you don't know which version to > use, start with Python 2.6.4; more > exis...
FOR MAC USERS: I'm a Python newbie and came across the exact same problem. I'm writing this so others don't waste several hours trying to figure this out. Here's what you do: * Do NOT install Python 3 for the above reasons, i.e. to avoid having to change all the Swampy code. Instead, download the latest version of Py...
1,650,095
I am reading the book [Think Python](http://www.greenteapress.com/thinkpython/) by Allen Downey. For chapter 4, one has to use a suite of modules called [Swampy](http://www.greenteapress.com/thinkpython/swampy/). I have downloaded and installed it. The problem is that the modules were written in Python 2 and I have Py...
2009/10/30
[ "https://Stackoverflow.com/questions/1650095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115139/" ]
It looks like tkinter is finally catching up with Python 3 - tkFont has become tkinter.font <http://docs.pythonsprints.com/python3_porting/py-porting.html> ``` #!/usr/bin/env python3.2 # -*- coding: utf-8 -*- # # font_ex.py # import tkinter top = tkinter.Tk() butt01 = tkinter.Button(top, text="Hello W...
There is a conversion tool for converting Python 2 code to work with Python 3: <http://svn.python.org/view/sandbox/trunk/2to3/> Not sure how this extends to 3rd party libraries but it might be worth passing this over the swampy code.
1,650,095
I am reading the book [Think Python](http://www.greenteapress.com/thinkpython/) by Allen Downey. For chapter 4, one has to use a suite of modules called [Swampy](http://www.greenteapress.com/thinkpython/swampy/). I have downloaded and installed it. The problem is that the modules were written in Python 2 and I have Py...
2009/10/30
[ "https://Stackoverflow.com/questions/1650095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115139/" ]
FOR MAC USERS: I'm a Python newbie and came across the exact same problem. I'm writing this so others don't waste several hours trying to figure this out. Here's what you do: * Do NOT install Python 3 for the above reasons, i.e. to avoid having to change all the Swampy code. Instead, download the latest version of Py...
There is a conversion tool for converting Python 2 code to work with Python 3: <http://svn.python.org/view/sandbox/trunk/2to3/> Not sure how this extends to 3rd party libraries but it might be worth passing this over the swampy code.
1,650,095
I am reading the book [Think Python](http://www.greenteapress.com/thinkpython/) by Allen Downey. For chapter 4, one has to use a suite of modules called [Swampy](http://www.greenteapress.com/thinkpython/swampy/). I have downloaded and installed it. The problem is that the modules were written in Python 2 and I have Py...
2009/10/30
[ "https://Stackoverflow.com/questions/1650095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115139/" ]
It looks like tkinter is finally catching up with Python 3 - tkFont has become tkinter.font <http://docs.pythonsprints.com/python3_porting/py-porting.html> ``` #!/usr/bin/env python3.2 # -*- coding: utf-8 -*- # # font_ex.py # import tkinter top = tkinter.Tk() butt01 = tkinter.Button(top, text="Hello W...
FOR MAC USERS: I'm a Python newbie and came across the exact same problem. I'm writing this so others don't waste several hours trying to figure this out. Here's what you do: * Do NOT install Python 3 for the above reasons, i.e. to avoid having to change all the Swampy code. Instead, download the latest version of Py...
54,140,796
I have a very large string consiting of a series of numbers separated by one or more spaces. Some of the numbers are equal to -123, and the rest can be any random number. ``` example_string = "102.3 42.89 98 812.7 374 5 -123 8 -123 13 -123 21..." ``` I would like to replace the values that are not equal ...
2019/01/11
[ "https://Stackoverflow.com/questions/54140796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691928/" ]
You can use this regex: ``` (^|\s)(?!-123(\s|$))-?[0-9.]+(?=\s|$) ``` It looks for the start of string or a space, not followed by -123 and space of end of string (using a negative lookahead) then some number of digits or a `.`, followed by either a space or end of string. Then you can replace with `\g<1>456` to tu...
You could match only the numbers between whitspace boundaries and the use re.sub with a callback function to check if the match is not `-123`. If it not, relace it with `456` ``` (?<!\S)-?\d+(?:\.\d+)?(?!\S) ``` **Explanation** * `(?<!\S)` Negative lookbehind to assert what is on the left is not a non-whitespace ch...
21,704,149
I am trying to configure Chronos to use custom mesos-docker executor present at <https://github.com/mesosphere/mesos-docker/> . Everytime I try to run the command it fails. I created the task using below command ``` echo '{"schedule":"R/2014-02-14T00:52:00Z/PT90M", "name":"testing_docker_executor", "command":"docker_...
2014/02/11
[ "https://Stackoverflow.com/questions/21704149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1213542/" ]
the problem is here: ``` size_t file; ``` size\_t is unsigned, so it will always be >=0 it should have been: ``` int file; ```
> > the open call returns something greater than 0 > > > `open` returns `int`, but you put in in an unsigned variable (`size_t` is usually unsigned), so you fail to detect when it is `<0`
65,732,046
here is my code ``` import numpy a = numpy.arange(0.5, 1.5, 0.1, dtype=numpy.float64) print(a) print(a.tolist()) >>>[0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4] >>>[0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999, 1.0999999999999999, 1.1999999999999997, 1.2999999999999998, 1.4] ``` When tryin...
2021/01/15
[ "https://Stackoverflow.com/questions/65732046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14922407/" ]
%%writefile is an IPython [cell magic](https://ipython.readthedocs.io/en/stable/interactive/magics.html#cell-magics), not a magic method. Cell magics are different by line magics because they are identified by a double %. IPyhton cell and line magics are specific to IPython. See [here](https://ipython.readthedocs.io/e...
If you mean this [magic command in iPython](https://ipython.readthedocs.io/en/stable/interactive/magics.html#cellmagic-writefile) (note: *command*, not *function*), then that's your answer; it is a specific iPython extension, not part of the Python language itself.
55,454,569
I am calling some java binary in unix environment wrapped inside python script When I call script from bash, output comes clean and also being stored in desired variable , However when i run the same script from Cron, Output stored(in a Variable) is incomplete my code: ``` command = '/opt/HP/BSM/PMDB/bin/abcAdminUt...
2019/04/01
[ "https://Stackoverflow.com/questions/55454569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8848689/" ]
``` alias py=python3.7 py filename.py ``` Add the alias to you `bash_aliases` to get it in every terminal
If you're using linux, you can shorten it to nothing by adding the line ```py #!/usr/bin/env python3.7 ``` to the top of your python file. Then `chmod 755 <filename.py>` and run it like any other executable.
59,544,848
I have captcha image as attached in this question. [![enter image description here](https://i.stack.imgur.com/wVbyF.png)](https://i.stack.imgur.com/wVbyF.png) I am trying to extract the text in the image. My following code is able to make all areas except the text and lines in white color ``` import cv2 from PIL im...
2019/12/31
[ "https://Stackoverflow.com/questions/59544848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8340105/" ]
My approach is based on the fact that the line is thinner than the characters. In this example I used blurring, threshold and morphology to get rid of the line between the characters. The result is this: [![enter image description here](https://i.stack.imgur.com/VwXMR.png)](https://i.stack.imgur.com/VwXMR.png) ```py i...
You can use CV2 functions like threshold, dilate, bitwise\_and and bitwise\_not for removing unwanted lines from captcha ``` import numpy as np import cv2 img = cv2.imread('captcha.jpg',0) horizontal_inv = cv2.bitwise_not(img) masked_img = cv2.bitwise_and(img, img, mask=horizontal_inv) masked_img_inv = cv2.bitwise_n...
3,106,994
I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms. I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to r...
2010/06/24
[ "https://Stackoverflow.com/questions/3106994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245968/" ]
In addition to `difflib` and other common subsequence libraries, if it's natural language text, you might look into stemming, which normalizes words to their root form. You can find several implementations in the Natural Language Toolkit ( <http://www.nltk.org/> ) library. You can also compare blobs of natural language...
Longest common chain? Perhaps this will help then: <http://en.wikipedia.org/wiki/Longest_common_subsequence_problem>
3,106,994
I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms. I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to r...
2010/06/24
[ "https://Stackoverflow.com/questions/3106994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245968/" ]
I don't know what "longest common [[chain? substring?]]" has to do with "percent difference", especially after seeing in a comment that you expect a very small % difference between two strings that differ by one character in the middle (so their longest common substring is about one half of the strings' length). Ignor...
Longest common chain? Perhaps this will help then: <http://en.wikipedia.org/wiki/Longest_common_subsequence_problem>
3,106,994
I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms. I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to r...
2010/06/24
[ "https://Stackoverflow.com/questions/3106994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245968/" ]
Longest common chain? Perhaps this will help then: <http://en.wikipedia.org/wiki/Longest_common_subsequence_problem>
Another area of interest might be the Levenshtein distance described [here](http://en.wikipedia.org/wiki/Levenshtein_distance).
3,106,994
I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms. I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to r...
2010/06/24
[ "https://Stackoverflow.com/questions/3106994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245968/" ]
I don't know what "longest common [[chain? substring?]]" has to do with "percent difference", especially after seeing in a comment that you expect a very small % difference between two strings that differ by one character in the middle (so their longest common substring is about one half of the strings' length). Ignor...
In addition to `difflib` and other common subsequence libraries, if it's natural language text, you might look into stemming, which normalizes words to their root form. You can find several implementations in the Natural Language Toolkit ( <http://www.nltk.org/> ) library. You can also compare blobs of natural language...
3,106,994
I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms. I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to r...
2010/06/24
[ "https://Stackoverflow.com/questions/3106994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245968/" ]
In addition to `difflib` and other common subsequence libraries, if it's natural language text, you might look into stemming, which normalizes words to their root form. You can find several implementations in the Natural Language Toolkit ( <http://www.nltk.org/> ) library. You can also compare blobs of natural language...
Another area of interest might be the Levenshtein distance described [here](http://en.wikipedia.org/wiki/Levenshtein_distance).
3,106,994
I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms. I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to r...
2010/06/24
[ "https://Stackoverflow.com/questions/3106994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245968/" ]
I don't know what "longest common [[chain? substring?]]" has to do with "percent difference", especially after seeing in a comment that you expect a very small % difference between two strings that differ by one character in the middle (so their longest common substring is about one half of the strings' length). Ignor...
Another area of interest might be the Levenshtein distance described [here](http://en.wikipedia.org/wiki/Levenshtein_distance).
36,732,614
Getting errors as below, when I follow **step 4** of the instruction from [Getting Started with ARC Open Source on Linux](https://chromium.googlesource.com/arc/arc/+/release-39.4410.148.0/docs/getting-started-open-source.md). OS is Ubuntu 14.04 LTS running in Hyper-V. > > UBUNTU14:~/arc$ ./configure > > ERROR:roo...
2016/04/20
[ "https://Stackoverflow.com/questions/36732614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/633210/" ]
The problem was bad ACLs on the files. I reached out to @elijah-taylor for a fix, it should now work!
faced same issue..fixed after running the following. ``` apt-get install gsutil apt-get install libwww-perl chmod +x ./third_party/tools/depot_tools/third_party/gsutil/gsutil ```
51,432,473
the problem ----------- I'm trying to use the `concurrent.futures` library to run a function on a list of "things". The code looks something like this. ``` import concurrent.futures import logging logger = logging.getLogger(__name__) def process_thing(thing, count): logger.info(f'starting processing for thing {...
2018/07/19
[ "https://Stackoverflow.com/questions/51432473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7830612/" ]
Here's a little recipe for a `DelaydLogger` class that puts all calls to `logger`'s methods into a list instead of actually performing the call, until you finally do a `flush` where they are all fired up. ``` from functools import partial class DelayedLogger: def __init__(self, logger): self.logger = logg...
First I modified @Jeronimo's answer to come up with this ``` class DelayedLogger: class ThreadLogger: """to be logged from a single thread""" def __init__(self, logger): self._call_stack = [] # list of (method, *args, **kwargs) tuples self.logger = logger self...
46,158,930
Have questions concerning the output of `apply()` method in python `pandas.DataFrame` ### Q1 - Why does this function returns a `pandas.DataFrame` **with the same format** as the input (`pandas.DataFrame`) when `apply` function returns an `array` with the same shape as input?. For instance ``` foo = pd.DataFrame([[...
2017/09/11
[ "https://Stackoverflow.com/questions/46158930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3941704/" ]
You can do it in one line by composing a regular expression pattern `"(item1|item2|item3)"` ``` let array = ["dee", "kamal"] let str = "Hello all how are you, I m here for deepak." let success = str.range(of: "(" + array.joined(separator: "|") + ")", options: .regularExpression) != nil ```
You should iterate over the array and for each element, call `str.contains`. ``` for word in array { if str.contains(word) { print("\(word) is part of the string") } else { print("Word not found") } } ```
46,158,930
Have questions concerning the output of `apply()` method in python `pandas.DataFrame` ### Q1 - Why does this function returns a `pandas.DataFrame` **with the same format** as the input (`pandas.DataFrame`) when `apply` function returns an `array` with the same shape as input?. For instance ``` foo = pd.DataFrame([[...
2017/09/11
[ "https://Stackoverflow.com/questions/46158930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3941704/" ]
You can do it in one line by composing a regular expression pattern `"(item1|item2|item3)"` ``` let array = ["dee", "kamal"] let str = "Hello all how are you, I m here for deepak." let success = str.range(of: "(" + array.joined(separator: "|") + ")", options: .regularExpression) != nil ```
You can do like this: ``` array.forEach { (item) in var isContains:Bool = str.contains(item) print(isContains) } ```
46,606,947
I'm trying to INSERT to MySQL from a CSV file, first 'column' in the file is a date in this format: ``` 31/08/2017; ``` then my column in the table is set as YYYY-MM-DD this is my code: ``` import datetime import csv import MySQLdb ... insertionSQL="INSERT INTO transactions (trans_date, tr...
2017/10/06
[ "https://Stackoverflow.com/questions/46606947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5794219/" ]
You will first have to create a path as a rounded rectangle. Then with each step in your animation you have to modify the eight segments of the path. This will only work with `Path` objects, not if your rectangle is a `Shape`. The segment points and the handles have to be set like this: [![rounded rect point and handl...
Change the corner size to the following ``` var cornerSize = circle.radius / 1; ```
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
Using '`Counter`' and '`defaultdict`' from Python: ``` l = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.833333333333333...
You could use something like this, ``` my_list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.8333333333333334, 3615]] compute...
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
Using '`Counter`' and '`defaultdict`' from Python: ``` l = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.833333333333333...
If you are happy using a 3rd party library, you can use Pandas. Given a list `L`: ``` import pandas as pd # construct dataframe from list df = pd.DataFrame(L, columns=['skills', 'value', 'id']) # define aggregation functions funcs = {'No_matched_skills': 'nunique', 'skills': lambda x: ', '.join(x.unique())} # apply...
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
``` from collections import defaultdict as dd d = dd(set) skillList = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.833...
You can use `itertools.groupby`: ``` import itertools _list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python', 0.8333333333333334, 361...
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
You probably want something like this: ``` from itertools import groupby from operator import itemgetter l = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', ...
You can use `itertools.groupby`: ``` import itertools _list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python', 0.8333333333333334, 361...
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
I modified your variable name from `list` to `lists` because while `list` is not a reserved keyword, you'd be overwriting the keyword for the list data structure. ``` lists = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0...
You can use `itertools.groupby`: ``` import itertools _list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python', 0.8333333333333334, 361...
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
I modified your variable name from `list` to `lists` because while `list` is not a reserved keyword, you'd be overwriting the keyword for the list data structure. ``` lists = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0...
``` from collections import defaultdict as dd d = dd(set) skillList = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.833...
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
Using '`Counter`' and '`defaultdict`' from Python: ``` l = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.833333333333333...
You can use `itertools.groupby`: ``` import itertools _list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python', 0.8333333333333334, 361...
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
I modified your variable name from `list` to `lists` because while `list` is not a reserved keyword, you'd be overwriting the keyword for the list data structure. ``` lists = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0...
You could use something like this, ``` my_list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.8333333333333334, 3615]] compute...
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
``` from collections import defaultdict as dd d = dd(set) skillList = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.833...
If you are happy using a 3rd party library, you can use Pandas. Given a list `L`: ``` import pandas as pd # construct dataframe from list df = pd.DataFrame(L, columns=['skills', 'value', 'id']) # define aggregation functions funcs = {'No_matched_skills': 'nunique', 'skills': lambda x: ', '.join(x.unique())} # apply...
51,308,114
I am again stuck with extract and compare list elements. I have following list of lists: ``` list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333...
2018/07/12
[ "https://Stackoverflow.com/questions/51308114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9758339/" ]
You probably want something like this: ``` from itertools import groupby from operator import itemgetter l = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', ...
You could use something like this, ``` my_list = [['laravel', 1.0, 54], ['laravel', 1.0, 3615], ['php', 1.0, 1405], ['php', 1.0, 5175], ['php', 1.0, 5176], ['php', 1.0, 54], ['php', 1.0, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.8333333333333334, 3615]] compute...
53,853,038
I have a python list `l` containing instances of the class `Element`: ```py class Element: def __init__(self, id, value): self.id = id self.value = value l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)] ``` Now I want to sum all `value` members of the classes `...
2018/12/19
[ "https://Stackoverflow.com/questions/53853038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7362422/" ]
There is (almost?) nothing that `itertools` cannot do. Take a look at [`groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby): ``` from itertools import groupby from operator import attrgetter class Element: def __init__(self, id, value): self.id = id self.value = value ...
One way would be to create a [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) that maps ids to sums of values. Then we can take those results and use them to build a new list of `Elements`. One way to do that is to use [`starmap`](https://docs.python.org/3/library/itertools.ht...
53,853,038
I have a python list `l` containing instances of the class `Element`: ```py class Element: def __init__(self, id, value): self.id = id self.value = value l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)] ``` Now I want to sum all `value` members of the classes `...
2018/12/19
[ "https://Stackoverflow.com/questions/53853038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7362422/" ]
There is (almost?) nothing that `itertools` cannot do. Take a look at [`groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby): ``` from itertools import groupby from operator import attrgetter class Element: def __init__(self, id, value): self.id = id self.value = value ...
You could also get the desired result using `set` to get just the unique ids and `sum` to total the values. For example: ``` class Element: def __init__(self, id, value): self.id = id self.value = value l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)] ids = set(...
53,853,038
I have a python list `l` containing instances of the class `Element`: ```py class Element: def __init__(self, id, value): self.id = id self.value = value l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)] ``` Now I want to sum all `value` members of the classes `...
2018/12/19
[ "https://Stackoverflow.com/questions/53853038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7362422/" ]
One way would be to create a [`defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) that maps ids to sums of values. Then we can take those results and use them to build a new list of `Elements`. One way to do that is to use [`starmap`](https://docs.python.org/3/library/itertools.ht...
You could also get the desired result using `set` to get just the unique ids and `sum` to total the values. For example: ``` class Element: def __init__(self, id, value): self.id = id self.value = value l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)] ids = set(...
26,710,578
I am using **python 2.7** .I am creating 3 lists (float values (if it matters at all)), i am using json object to save it in a file. **Say for eg.** ``` L1=[1,2,3,4,5] L2=[11,22,33,44,55] L3=[22,33,44,55,66] b={} b[1]=L1 b[2]=L2 b[3]=L3 json.dump(b,open("file.txt","w")) ``` I need to read these values back from ...
2014/11/03
[ "https://Stackoverflow.com/questions/26710578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2126725/" ]
try ``` content = json.load(open('file.txt')) ``` or using a the [with context manager](https://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for) to close the file for you: ``` with open('file.txt') as f: content = json.load(f) ``` Also, read the library's [documentation](https://d...
I used this following code: ``` import json path=r"file.txt" for line in open(path): obj = json.loads(line) x=obj['1'] y=obj['2'] z=obj['3'] ``` Now, i will have the List *L1 in x*, *L2 in y* and *L3 in z*
8,711,794
I am looking for the simplest **generic** way to convert this python list: ``` x = [ {"foo":"A", "bar":"R", "baz":"X"}, {"foo":"A", "bar":"R", "baz":"Y"}, {"foo":"B", "bar":"S", "baz":"X"}, {"foo":"A", "bar":"S", "baz":"Y"}, {"foo":"C", "bar":"R", "baz":"Y"}, ] ``` into: ...
2012/01/03
[ "https://Stackoverflow.com/questions/8711794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248922/" ]
``` #!/usr/bin/env python3 from itertools import groupby from pprint import pprint x = [ {"foo":"A", "bar":"R", "baz":"X"}, {"foo":"A", "bar":"R", "baz":"Y"}, {"foo":"B", "bar":"S", "baz":"X"}, {"foo":"A", "bar":"S", "baz":"Y"}, {"foo":"C", "bar":"R", "baz":"Y"}, ] def fun(...
I would define a function that performs a single grouping step like this: ``` from itertools import groupby def group(items, key, subs_name): return [{ key: g, subs_name: [dict((k, v) for k, v in s.iteritems() if k != key) for s in sub] } for g, sub in groupby(sorted(items, key=lamb...
8,711,794
I am looking for the simplest **generic** way to convert this python list: ``` x = [ {"foo":"A", "bar":"R", "baz":"X"}, {"foo":"A", "bar":"R", "baz":"Y"}, {"foo":"B", "bar":"S", "baz":"X"}, {"foo":"A", "bar":"S", "baz":"Y"}, {"foo":"C", "bar":"R", "baz":"Y"}, ] ``` into: ...
2012/01/03
[ "https://Stackoverflow.com/questions/8711794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248922/" ]
``` #!/usr/bin/env python3 from itertools import groupby from pprint import pprint x = [ {"foo":"A", "bar":"R", "baz":"X"}, {"foo":"A", "bar":"R", "baz":"Y"}, {"foo":"B", "bar":"S", "baz":"X"}, {"foo":"A", "bar":"S", "baz":"Y"}, {"foo":"C", "bar":"R", "baz":"Y"}, ] def fun(...
This is a simple loop over the data, no recursion. An auxiliary tree where the values are dictionary keys is used as an index to the result tree while it is being built. ``` def make_tree(diclist, keylist): indexroot = {} root = {} for d in diclist: walk = indexroot parent = root fo...
8,552,556
I have never used python in my life. I need to make a little fix to a given code. I need to replace this ``` new_q = q[:q.index('?')] + str(random.randint(1,rand_max)) + q[q.index('?')+1:] ``` with something that replace all of the occurrence of ? with a random, different number. how can I do that?
2011/12/18
[ "https://Stackoverflow.com/questions/8552556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/182416/" ]
``` import re import random a = 'abc?def?ghi?jkl' rand_max = 9 re.sub(r'\?', lambda x:str(random.randint(1,rand_max)), a) # returns 'abc3def4ghi6jkl' ``` or without regexp: ``` import random a = 'abc?def?ghi?jkl' rand_max = 9 while '?' in a: a = a[:a.index('?')] + str(random.randint(1,rand_max)) + a[a.index('?...
If you need all the numbers to be different, just using a new random number for each occurrence of `?` won't be enough -- a random number might occur twice. You could use the following code in this case: ``` random_numbers = iter(random.sample(range(1, rand_max + 1), q.count("?"))) new_q = "".join(c if c != "?" else s...
37,803,628
I'm trying to create a CNN using Tensorflow that classifies images into **16 classes**. My original image size is 72x72x1, and my network is structured like this: ``` # Network n_input = dim n_output = nclass # 16 weights = { 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32], stddev=0.1)), 'wc2': tf.Var...
2016/06/14
[ "https://Stackoverflow.com/questions/37803628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1578098/" ]
Given your code (and guessing what is missing in it), I think you have these parameters and results (correct me if wrong): * `batch_size`: 1 * `num_classes`: 16 * labels `y`: type int, shape `[batch_size, 1]` * outputs `_pred`: type float32, **should be** shape `[batch_size, num_classes]` --- In your code, you only ...
Its hard to tell from what you provided, but it seems like you feed inputs with a batch size of 6, but only provide one label for them. Where does your data come from?
20,133,316
I have the following code which works: ``` import xml.etree.ElementTree as etree def get_path(self): parent = '' path = self.tag sibs = self.parent.findall(self.tag) if len(sibs) > 1: path = path + '[%s]'%(sibs.index(self)+1) current_node = self while True: parent = current_no...
2013/11/21
[ "https://Stackoverflow.com/questions/20133316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2723675/" ]
If you *need* parents, use lxml instead - it tracks parents internally, and is still C behind the scenes so it's very fast. However... be aware that there is a tradeoff in tracking parents, in that a given node can only have a single parent. This isn't usually a problem, however, if you do something like the following...
you can just use xpath, for example: ``` import lxml.html def get_path(): for e in doc.xpath("//b//*"): print e ``` should work, didn't test it though...
66,320,831
TLDR; ===== It's possible to configure the Beam portable runner with the spark configurations? More precisely, it's possible to configure the `spark.driver.host` in the Portable Runner? Motivation ========== Currently, we have airflow implemented in a Kubernetes cluster, and aiming to use TensorFlow Extended we need...
2021/02/22
[ "https://Stackoverflow.com/questions/66320831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13454548/" ]
I have three solutions to choose from depending on your deployment requirements. In order of difficulty: 1. Use the Spark "uber jar" job server. This starts an embedded job server inside the Spark master, instead of using a standalone job server in a container. This would simplify your deployment a lot, since you woul...
Let me revise the answer. The Job server need to able to communicate with the workers vice verse. The error of keep exiting is due to this. You need to configure such that they can communicate. A k8s headless service able to solve this. reference of workable example at <https://github.com/cometta/python-apache-beam-sp...
55,799,546
I am trying to make a simple app in kivy(a python package) that gets a text from a TextInput field and when a button is clicked it returns a text in Hebrew that will displayed on another TextInput, Everything seems to be working just fine but I encounter the problem that a TextInput field in Kivy could not show the Heb...
2019/04/22
[ "https://Stackoverflow.com/questions/55799546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10139792/" ]
Okay! So it didn't take a long time because someone on a discord server helped me and all I had to do was to just switch the text area font because the previous one didn't have an Hebrew font. To do it I downloaded the font "Arial" added it to my folder with the main script, I imported `from kivy.core.text import Label...
you should also reverse the text that the user type, i did this: ``` class HebrowTextInput(TextInput): def __init__(self, **kwargs): super(HebrowTextInput, self).__init__(font_name='DejaVuSans.ttf', halign="right", **kwargs) self.multiline = False def keyboard_on_key_down(self, window, keycod...
34,178,172
I have created a table: ``` cursor.execute("CREATE TABLE articles (title varchar PRIMARY KEY, pubDate timestamp with time zone);") ``` I inserted a timestamp like this: ``` timestamp = date_datetime.strftime("%Y-%m-%d %H:%M:%S+00") cursor.execute("INSERT INTO articles VALUES (%s, %s)", (title, time...
2015/12/09
[ "https://Stackoverflow.com/questions/34178172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4772958/" ]
Python's `datetime` objects are automatically [adapted](http://initd.org/psycopg/docs/usage.html#python-types-adaptation) into SQL by `psycopg2`, you don't need to stringify them: ``` cursor.execute("INSERT INTO articles VALUES (%s, %s)", (title, datetime_obj)) ``` To read the rows returned by a `SE...
After some more googling I think I figured it out. If I change: ``` print(row) ``` to ``` print(row[0]) ``` It actually works. I guess this is because row is a tuple and this is way to unpack the tuple correctly.
34,178,172
I have created a table: ``` cursor.execute("CREATE TABLE articles (title varchar PRIMARY KEY, pubDate timestamp with time zone);") ``` I inserted a timestamp like this: ``` timestamp = date_datetime.strftime("%Y-%m-%d %H:%M:%S+00") cursor.execute("INSERT INTO articles VALUES (%s, %s)", (title, time...
2015/12/09
[ "https://Stackoverflow.com/questions/34178172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4772958/" ]
After some more googling I think I figured it out. If I change: ``` print(row) ``` to ``` print(row[0]) ``` It actually works. I guess this is because row is a tuple and this is way to unpack the tuple correctly.
``` import pytz title ='The Title' tz = pytz.timezone("US/Pacific") timestamp = tz.localize(datetime(2015, 05, 20, 13, 56, 02), is_dst=None) query = "insert into articles values (%s, %s)" print cursor.mogrify(query, (title, timestamp)) cursor.execute(query, (title, timestamp)) conn.commit() query = "select * from ar...
34,178,172
I have created a table: ``` cursor.execute("CREATE TABLE articles (title varchar PRIMARY KEY, pubDate timestamp with time zone);") ``` I inserted a timestamp like this: ``` timestamp = date_datetime.strftime("%Y-%m-%d %H:%M:%S+00") cursor.execute("INSERT INTO articles VALUES (%s, %s)", (title, time...
2015/12/09
[ "https://Stackoverflow.com/questions/34178172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4772958/" ]
Python's `datetime` objects are automatically [adapted](http://initd.org/psycopg/docs/usage.html#python-types-adaptation) into SQL by `psycopg2`, you don't need to stringify them: ``` cursor.execute("INSERT INTO articles VALUES (%s, %s)", (title, datetime_obj)) ``` To read the rows returned by a `SE...
``` import pytz title ='The Title' tz = pytz.timezone("US/Pacific") timestamp = tz.localize(datetime(2015, 05, 20, 13, 56, 02), is_dst=None) query = "insert into articles values (%s, %s)" print cursor.mogrify(query, (title, timestamp)) cursor.execute(query, (title, timestamp)) conn.commit() query = "select * from ar...
31,581,902
How to clone with disabled SSL checking, using GitPython library. The following code ... ``` import git x = git.Repo.clone_from('https://xxx', '/home/xxx/lala') ``` ... yields this error: ``` Error: fatal: unable to access 'xxx': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt C...
2015/07/23
[ "https://Stackoverflow.com/questions/31581902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4319148/" ]
The two following methods have been tested with GitPython 2.0.8 but should be working at least since 1.0.2 (from the doc). As suggested by @Byron: ```py git.Repo.clone_from( 'https://example.net/path/to/repo.git', 'local_destination', branch='master', depth=1, env={'GIT_SSL_NO_VERIFY': '1'}, ) ``` As sugges...
It seems easiest to pass the `GIT_SSL_NO_VERIFY` environment variable to all git invocations. Unfortunately [`Git.update_environment(...)`](http://gitpython.readthedocs.org/en/stable/reference.html?highlight=update_environment#git.cmd.Git.update_environment) can only be used on an existing instance, which is why you wo...
45,994,973
I have a Numpy one-dimensional array of 1 and 0. for e.g ``` a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) ``` I want to count the continuous 0s and 1s in the array and output something like this ``` [1,3,7,1,1,2,3,2,2] ``` What I do atm is ``` np.diff(np.where(np.abs(np.diff(a)) == 1)[0]) ``` an...
2017/09/01
[ "https://Stackoverflow.com/questions/45994973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1947744/" ]
Here's one vectorized approach - ``` np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size]) ``` Sample run - ``` In [208]: a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) In [209]: np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size]) Out[209]: array([1, 3, 7, 1, 1, 2, 3, 2, 2]) ``` Faster one with `b...
Using `groupby` from `itertools` ``` from itertools import groupby a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) grouped_a = [ sum(1 for i in g) for k,g in groupby(a)] ```
45,994,973
I have a Numpy one-dimensional array of 1 and 0. for e.g ``` a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) ``` I want to count the continuous 0s and 1s in the array and output something like this ``` [1,3,7,1,1,2,3,2,2] ``` What I do atm is ``` np.diff(np.where(np.abs(np.diff(a)) == 1)[0]) ``` an...
2017/09/01
[ "https://Stackoverflow.com/questions/45994973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1947744/" ]
Here's one vectorized approach - ``` np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size]) ``` Sample run - ``` In [208]: a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) In [209]: np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size]) Out[209]: array([1, 3, 7, 1, 1, 2, 3, 2, 2]) ``` Faster one with `b...
I found a similar method to yours, just that this code finds the first and the last count separately. The answer is detailed in the code below: ```py import numpy as np a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) print(f'a: {a}') diff_a = np.diff(a) print(f'diff_a: {diff_a}') non_zero_pos_arr = np.w...
45,994,973
I have a Numpy one-dimensional array of 1 and 0. for e.g ``` a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) ``` I want to count the continuous 0s and 1s in the array and output something like this ``` [1,3,7,1,1,2,3,2,2] ``` What I do atm is ``` np.diff(np.where(np.abs(np.diff(a)) == 1)[0]) ``` an...
2017/09/01
[ "https://Stackoverflow.com/questions/45994973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1947744/" ]
Using `groupby` from `itertools` ``` from itertools import groupby a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) grouped_a = [ sum(1 for i in g) for k,g in groupby(a)] ```
I found a similar method to yours, just that this code finds the first and the last count separately. The answer is detailed in the code below: ```py import numpy as np a = np.array([0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0]) print(f'a: {a}') diff_a = np.diff(a) print(f'diff_a: {diff_a}') non_zero_pos_arr = np.w...