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", 1): raise RuntimeError( f"This example is not compatible with your current PTB version {TG_VER}. To view the " f"{TG_VER} version of this example, " f"visit https://github.com/python-telegram-bot/python-telegram-bot/tree/v{TG_VER}/examples" ) ``` It installs PyPi version 13.12 but example checks different version v20. So, the error is reasonable. How can I let example working?
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) ``` Output assuming banana is a NaN: ``` Fruits 0 Apple 1 Pear 2 Orange 3 Mango 4 NaN ```
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 * sum(1), is summing the df row by row. Since values in row are strings, it will join them together **Example Usage** ``` from io import StringIO # Create DataFrame from OP data s = '''Fruit1,Fruit2,Fruit3 NaN,Apple,NaN Pear,NaN,NaN NaN,NaN,Orange Mango,NaN,NaN NaN,banana,NaN''' df = pd.read_csv(StringIO(s)) print(df) ``` *Initial DataFrame* ``` Fruit1 Fruit2 Fruit3 0 NaN Apple NaN 1 Pear NaN NaN 2 NaN NaN Orange 3 Mango NaN NaN 4 NaN banana NaN df['New']=df.fillna('').sum(1) print(df) ``` *Updated DataFrame* ``` Fruit1 Fruit2 Fruit3 new 0 NaN Apple NaN Apple 1 Pear NaN NaN Pear 2 NaN NaN Orange Orange 3 Mango NaN NaN Mango 4 NaN banana NaN banana ```
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", 1): raise RuntimeError( f"This example is not compatible with your current PTB version {TG_VER}. To view the " f"{TG_VER} version of this example, " f"visit https://github.com/python-telegram-bot/python-telegram-bot/tree/v{TG_VER}/examples" ) ``` It installs PyPi version 13.12 but example checks different version v20. So, the error is reasonable. How can I let example working?
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 ``` ``` 0 Apple 1 Pear 2 Orange 3 None Name: fruits, dtype: object ``` (or [`ffill()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ffill.html) and use the last column) It also works for rows containing `None` only.
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 * sum(1), is summing the df row by row. Since values in row are strings, it will join them together **Example Usage** ``` from io import StringIO # Create DataFrame from OP data s = '''Fruit1,Fruit2,Fruit3 NaN,Apple,NaN Pear,NaN,NaN NaN,NaN,Orange Mango,NaN,NaN NaN,banana,NaN''' df = pd.read_csv(StringIO(s)) print(df) ``` *Initial DataFrame* ``` Fruit1 Fruit2 Fruit3 0 NaN Apple NaN 1 Pear NaN NaN 2 NaN NaN Orange 3 Mango NaN NaN 4 NaN banana NaN df['New']=df.fillna('').sum(1) print(df) ``` *Updated DataFrame* ``` Fruit1 Fruit2 Fruit3 new 0 NaN Apple NaN Apple 1 Pear NaN NaN Pear 2 NaN NaN Orange Orange 3 Mango NaN NaN Mango 4 NaN banana NaN banana ```
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 cellpadding="0" cellspacing="0" id="programmeDescriptor" width="100%"> <tr> <td> <table cellpadding="5" cellspacing="0" class="borders" width="100%"> <tr> <th colspan="1"> Awards </th> </tr> <tr> </tr> <tr> <td> Ordinary Bachelor Degree </td> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td> <table cellpadding="5" cellspacing="0" class="borders"> <tr> <th width="160"> Programme Code: </th> <td width="150"> CodeValue </td> </tr> </table> </td> <td width="5"> </td> <td> <table cellpadding="5" cellspacing="0" class="borders"> <tr> <th width="160"> Mode of Delivery: </th> <td width="150"> Full Time </td> </tr> </table> </td> <td width="5"> </td> <td> <table cellpadding="5" cellspacing="0" class="borders"> <tr> <th width="160"> No. of Semesters: </th> <td width="150"> 6 </td> </tr> </table> </td> </tr> <tr> <td> <table cellpadding="5" cellspacing="0" class="borders"> <tr> <th width="160"> NFQ Level: </th> <td width="150"> 7 </td> </tr> </table> </td> </tr> <tr> <td> <table cellpadding="5" cellspacing="0" class="borders"> <tr> <th width="160"> Embedded Award: </th> <td width="150"> No </td> </tr> </table> </td> </tr> </table> <table cellpadding="5" cellspacing="0" class="borders" width="100%"> <tr> <th width="160"> Department: </th> <td> Computing </td> </tr> </table> <div class="pageBreak"> </div> <h3> Programme Outcomes </h3> <p class="info"> On successful completion of this programme the learner will be able to : </p> <table cellpadding="5" cellspacing="0" class="borders" width="100%"> <tr> <th width="30"> PO1 </th> <td class="head" colspan="2"> Knowledge - Breadth </td> </tr> <tr> <td class="head" width="30"> </td> <td class="head" width="30"> (a) </td> <td> • Some block of text </tr> <tr> <th width="30"> PO2 </th> <td class="head" colspan="2"> Knowledge - Kind </td> </tr> <tr> <td class="head" width="30"> </td> <td class="head" width="30"> (a) </td> <td> • Some block of text </td> </tr> <tr> <th width="30"> PO3 </th> <td class="head" colspan="2"> Skill - Range </td> </tr> <tr> <td class="head" width="30"> </td> <td class="head" width="30"> (a) </td> <td> • Some block of text </td> </tr> <tr> <th width="30"> PO4 </th> <td class="head" colspan="2"> Skill - Selectivity </td> </tr> <tr> <td class="head" width="30"> </td> <td class="head" width="30"> (a) </td> <td> • Some block of text </td> </tr> <tr> <th width="30"> PO5 </th> <td class="head" colspan="2"> Competence - Context </td> </tr> <tr> <td class="head" width="30"> </td> <td class="head" width="30"> (a) </td> <tdSome block of text </td> </tr> <tr> <th width="30"> PO6 </th> <td class="head" colspan="2"> Competence - Role </td> </tr> <tr> <td class="head" width="30"> </td> <td class="head" width="30"> (a) </td> <td> • Some block of text </td> </tr> <tr> <th width="30"> PO7 </th> <td class="head" colspan="2"> Competence - Learning to Learn </td> </tr> <tr> <td class="head" width="30"> </td> <td class="head" width="30"> (a) </td> <td> • Some block of text </td> </tr> <tr> <th width="30"> PO8 </th> <td class="head" colspan="2"> Competence - Insight </td> </tr> <tr> <td class="head" width="30"> </td> <td class="head" width="30"> (a) </td> <td> • The graduate will demonstrate the ability to specify, design and build an IT system or research &amp; report on a current IT topic </td> </tr> </table> <div class="pageBreak"> </div> <h3> Semester Schedules </h3> <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td colspan="2"> <h4> Stage 1 / Semester 1 </h4> </td> </tr> <tr> <td colspan="2"> <table cellpadding="5" cellspacing="0" class="borders" width="100%"> <tr> <td class="head" colspan="2"> Mandatory </td> </tr> <tr> <th width="50"> Module Code </th> <th> Module Title </th> </tr> <tr> <td> Code </td> <td <a href="index.cfm/page/module/moduleId/3897" target="_blank"> Web &amp; User Experience </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3881" target="_blank"> Software Development 1 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/1645" target="_blank"> Computer Architecture </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2328" target="_blank"> Discrete Mathematics 1 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3848" target="_blank"> Business &amp; Information Systems </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2054" target="_blank"> Learning to Learn at Third Level </a> </td> </tr> </table> </td> </tr> </table> <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td colspan="2"> <h4> Stage 1 / Semester 2 </h4> </td> </tr> <tr> <td colspan="2"> <table cellpadding="5" cellspacing="0" class="borders" width="100%"> <tr> <td class="head" colspan="2"> Mandatory </td> </tr> <tr> <th width="50"> Module Code </th> <th> Module Title </th> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3886" target="_blank"> Software Development 2 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3895" target="_blank"> Object Oriented Systems Analysis </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3875" target="_blank"> Database Fundamentals </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3874" target="_blank"> Operating Systems Fundamentals </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2330" target="_blank"> Statistics </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2527" target="_blank"> Social Media Communications </a> </td> </tr> </table> </td> </tr> </table> <div class="pageBreak"> </div> <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td colspan="2"> <h4> Stage 2 / Semester 1 </h4> </td> </tr> <tr> <td colspan="2"> <table cellpadding="5" cellspacing="0" class="borders" width="100%"> <tr> <td class="head" colspan="2"> Mandatory </td> </tr> <tr> <th width="50"> Module Code </th> <th> Module Title </th> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3877" target="_blank"> Web &amp; Mobile Design &amp; Development </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3876" target="_blank"> Database Design And Programming </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3869" target="_blank"> Software Development 3 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3873" target="_blank"> Software Quality Assurance and Testing </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3629" target="_blank"> Networking 1 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2477" target="_blank"> Discrete Mathematics 2 </a> </td> </tr> </table> </td> </tr> </table> <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td colspan="2"> <h4> Stage 2 / Semester 2 </h4> </td> </tr> <tr> <td colspan="2"> <table cellpadding="5" cellspacing="0" class="borders" width="100%"> <tr> <td class="head" colspan="2"> Mandatory </td> </tr> <tr> <th width="50"> Module Code </th> <th> Module Title </th> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3862" target="_blank"> Project </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3911" target="_blank"> Object Oriented Analysis &amp; Design 1 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3877" target="_blank"> Web &amp; Mobile Design &amp; Development </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3630" target="_blank"> Networking 2 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3870" target="_blank"> Software Development 4 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2476" target="_blank"> Management Science </a> </td> </tr> </table> </td> </tr> </table> <div class="pageBreak"> </div> <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td colspan="2"> <h4> Stage 3 / Semester 1 </h4> </td> </tr> <tr> <td colspan="2"> <table cellpadding="5" cellspacing="0" class="borders" width="100%"> <tr> <td class="head" colspan="2"> Mandatory </td> </tr> <tr> <th width="50"> Module Code </th> <th> Module Title </th> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3911" target="_blank"> Object Oriented Analysis &amp; Design 1 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3899" target="_blank"> Operating Systems </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/1721" target="_blank"> Cloud Services &amp; Distributed Computing </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2580" target="_blank"> Innovation &amp; Entrepreneurship </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3878" target="_blank"> Web Application Development </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/1689" target="_blank"> Algorithms and Data Structures 1 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2025" target="_blank"> Logic and Problem Solving </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3896" target="_blank"> Advanced Databases </a> </td> </tr> </table> </td> </tr> </table> <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td colspan="2"> <h4> Stage 3 / Semester 2 </h4> </td> </tr> <tr> <td colspan="2"> <table cellpadding="5" cellspacing="0" class="borders" width="100%"> <tr> <td class="head" colspan="2"> Mandatory </td> </tr> <tr> <th width="50"> Module Code </th> <th> Module Title </th> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2465" target="_blank"> Project </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/1728" target="_blank"> Algorithms and Data Structures 2 </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/1675" target="_blank"> Network Management </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2025" target="_blank"> Logic and Problem Solving </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/3899" target="_blank"> Operating Systems </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/2580" target="_blank"> Innovation &amp; Entrepreneurship </a> </td> </tr> <tr> <td> Code </td> <td> <a href="index.cfm/page/module/moduleId/1679" target="_blank"> Object Oriented Analysis &amp; Design 2 </a> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> ```
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 combined text of selected elements ``` Also there's another issue. Your text is not in its own element. In order to get the textnodes in your current element, you could call [`.contents()`](https://api.jquery.com/contents/). jQuery does not treat text nodes like regular elements, though, so I would be careful doing any additional operations on them. You can retrieve the text like such: ``` $("#Data").contents().eq(0).text() // -> 'Domain Name: example.com' $("#Data").contents().eq(2).text() // -> 'Registry: 12345' ``` **[Fiddle](http://jsfiddle.net/xf4s16x1/)**
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 $(document).ready(function() { var content = $('div#Data.info').eq(0).text(); var lines = content.split("\n").filter(Boolean) console.log(lines); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="info" id="Data"> Domain Name: example.com <br> Registry: 12345 <br> </div> ```
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 values. This is what I tried but it's returning an error. For some reason my data was getting converted from str to float so I forced it to str. ``` def splitter(row): row = str(row) return row.split() df['date'],df['time'] = df['last_created'].apply(splitter) ``` Error: ``` --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-47-e5a9cf968714> in <module>() 7 return row.split() 8 ----> 9 df['date'],df['time'] = df['last_created'].apply(splitter) 10 df 11 #splitter(df.iloc[1,1]) ValueError: too many values to unpack (expected 2) ```
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 ``` $now = time(); foreach ($events->results() as $e): if (strtotime($e->event_date) >= $now) {// check for greater then equal to ?> <h1>Show Event</h1> <?php } else { echo "<h1>DON'T Show Event</h1>"; } endforeach; ```
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>"; } endforeach; ?> ```
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 the documentation, but I saw nothing really (except base, but I don't get what that is). BTW, here is my setup file: ``` import cx_Freeze exe = [cx_Freeze.Executable("myGame.py")] cx_Freeze.setup( name = "GameName", version = "1.0", options = {"build_exe": {"packages": ["pygame", "random", "ConfigParser", "sys"], "include_files": [ "images", "settings.ini", "arialbd.ttf"]}}, executables = exe ) ``` Here's a screen shot of what happens when I launch the exe: ![ScreenShot](https://i.stack.imgur.com/LniBW.jpg)
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_Freeze.setup( name = "GameName", version = "1.0", options = {"build_exe": {"packages": ["pygame", "random", "ConfigParser", "sys"], "include_files": ["images", "settings.ini", "arialbd.ttf"]}}, executables = exe ) ```
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( "python_fu_something", "Blah de blah", "Blah de blah", "Blah de blah", "Blah de blah", "2013", "<Image>/File/Save as blah...", "*", [ (PF_DIRNAME, "directory", "Directory to save files to", "/") ], [], do_the_foo ) ``` Naturally this means that the dialog pops up with "/" as the default directory. That's not ideal. I'd like it to start with the path to the currently loaded image if known and then fall back to "/" if the currently loaded image has no path (not saved, whatever). But to get there I need to know how to replace "/" with a function. I've tried doing just that (create a function, reference it in the PF\_DIRNAME line) but no joy (and no error message, either).
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 only give some recommendation. Define a datastructure for your data. Preallocate a big enough array, and then put ringbuffer mechanism, that handles the indexes of where the ISR can currently write. For the ISR this should be rather fast, because it just fills outr the values in the next empty slot. In the main routine you can then print at leisure. However, you have to synchronize the access and also take care that the ISR doesn't produce data much faster than you can discard it. At least with a proper ringbuffer, it shouldn't crash, but you might loose information.
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', ',') print(number) # 5,123,673.682 ``` Thanks
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', ',') print(number) # 5,123,673.682 ``` Thanks
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: print('Incorrect fold') ``` i receive this error: `IndexError: list index out of range` yet here are my files in my fold ``` model_apparentflow_net_fold0_epoch050.h5 model_apparentflow_net_fold1_epoch050.h5 model_apparentflow_net_fold2_epoch050.h5 il y a 7 jours17.9 MB model_apparentflow_net_fold3_epoch050.h5 model_apparentflow_net_fold4_epoch050.h5 model_apparentflow_net_fold5_epoch050.h5 module_apparentflow_net.py ``` so I don't understand why the python terminal tells me that I reference an index that does not exist yet it exists. Please could someone help me? thank you so much for all answers
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_apparentflow_net_fold4_epoch050.h5", "model_apparentflow_net_fold5_epoch050.h5", ] def train_apparentflow_net(model_list): code_path = config.code_dir fold = model_list[1] # specify model here 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: print('Incorrect fold') ```
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 of subdictionaries should happen on the fly. What is the most elegant way to allow something equivalent - maybe using decorators on the standard `<type 'dict'>`?
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.html#collections.defaultdict). For two levels this is straightforward: ``` >>> from collections import defaultdict >>> d = defaultdict(dict) >>> d['key']['subkey'] = 'value' >>> d['key']['subkey'] 'value' ``` For three it's slightly more complex: ``` >>> d = defaultdict(lambda: defaultdict(dict)) >>> d['key']['subkey']['subkey2'] = 'value' >>> d['key']['subkey']['subkey2'] 'value' ``` Four and more levels are left as an exercise for the reader. :-)
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 of subdictionaries should happen on the fly. What is the most elegant way to allow something equivalent - maybe using decorators on the standard `<type 'dict'>`?
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.html#collections.defaultdict). For two levels this is straightforward: ``` >>> from collections import defaultdict >>> d = defaultdict(dict) >>> d['key']['subkey'] = 'value' >>> d['key']['subkey'] 'value' ``` For three it's slightly more complex: ``` >>> d = defaultdict(lambda: defaultdict(dict)) >>> d['key']['subkey']['subkey2'] = 'value' >>> d['key']['subkey']['subkey2'] 'value' ``` Four and more levels are left as an exercise for the reader. :-)
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/85269428/python-nested-defaultdicts> It's definitely not pretty to have to use lambdas to implements the inner defaulted collections, but apparently necessary.
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 of subdictionaries should happen on the fly. What is the most elegant way to allow something equivalent - maybe using decorators on the standard `<type 'dict'>`?
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/85269428/python-nested-defaultdicts> It's definitely not pretty to have to use lambdas to implements the inner defaulted collections, but apparently necessary.
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**%27]' I tried ``` 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%d%27]' %i ``` I get no error message but it says ``` b Traceback (most recent call last): File "<ipython-input-79-89e6c98d9288>", line 1, in <module> b NameError: name 'b' is not defined ``` So I think the difficult part is that there is no space in between the string... How can I handle this?
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**%27]' I tried ``` 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%d%27]' %i ``` I get no error message but it says ``` b Traceback (most recent call last): File "<ipython-input-79-89e6c98d9288>", line 1, in <module> b NameError: name 'b' is not defined ``` So I think the difficult part is that there is no space in between the string... How can I handle this?
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 values of interest with `val, in lst` and use implicit string concatenation along with an f-string at the end to substitute the value.
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**%27]' I tried ``` 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%d%27]' %i ``` I get no error message but it says ``` b Traceback (most recent call last): File "<ipython-input-79-89e6c98d9288>", line 1, in <module> b NameError: name 'b' is not defined ``` So I think the difficult part is that there is no space in between the string... How can I handle this?
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 values of interest with `val, in lst` and use implicit string concatenation along with an f-string at the end to substitute the value.
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' ``` The code is as follows: ``` import socket target_host = "www.google.com" target_port = 80 #create socket object client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #connect the client client.connect((target_host,target_port)) #send some data data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n" client.send(data) #this is where I get the error #receive some data response = client.recv(4096) print(response) ``` Thanks for your help in advance!
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 would use [`bytes.decode()`](https://docs.python.org/3/library/stdtypes.html#bytes.decode) to receive the data: ``` import socket target_host = "www.google.com" target_port = 80 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((target_host,target_port)) data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n" client.send(data.encode('utf-8')) response = client.recv(4096).decode('utf-8') print(response) ```
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.socket.send) takes a bytes parameter. Thus you have to convert your string `data` into bytes using [`str.encode()`](https://docs.python.org/3/library/stdtypes.html#str.encode). So your code might look like this instead. ``` import socket target_host = "www.google.com" target_port = 80 #create socket object client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #connect the client client.connect((target_host,target_port)) #send some data data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n" client.send(data.encode('utf-8')) #receive some data response = client.recv(4096) print(response) ```
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' ``` The code is as follows: ``` import socket target_host = "www.google.com" target_port = 80 #create socket object client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #connect the client client.connect((target_host,target_port)) #send some data data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n" client.send(data) #this is where I get the error #receive some data response = client.recv(4096) print(response) ``` Thanks for your help in advance!
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 would use [`bytes.decode()`](https://docs.python.org/3/library/stdtypes.html#bytes.decode) to receive the data: ``` import socket target_host = "www.google.com" target_port = 80 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((target_host,target_port)) data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n" client.send(data.encode('utf-8')) response = client.recv(4096).decode('utf-8') print(response) ```
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 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((target_host,target_port)) data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n" client.send(data.encode('utf-8')) response = client.recv(4096).decode('utf-8') print(response) ```
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' ``` The code is as follows: ``` import socket target_host = "www.google.com" target_port = 80 #create socket object client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #connect the client client.connect((target_host,target_port)) #send some data data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n" client.send(data) #this is where I get the error #receive some data response = client.recv(4096) print(response) ``` Thanks for your help in advance!
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 would use [`bytes.decode()`](https://docs.python.org/3/library/stdtypes.html#bytes.decode) to receive the data: ``` import socket target_host = "www.google.com" target_port = 80 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((target_host,target_port)) data = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n" client.send(data.encode('utf-8')) response = client.recv(4096).decode('utf-8') print(response) ```
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\r\nHost: google.com\r\n\r\n") response = s.recv(4096) print(response) ```
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 emulate the same thing using python..i don't want to use pyCurl or send this line through os.system()..is there ny way out using raw python??
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 byte string # gzip and deflate transfer-encodings automatically decoded r.json() # return python object from json! this is what you probably want! ```
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 `nohup.out` but I don't need it there. Therefore I'm looking for a platform independent solution. `os.spawnlp(os.P_DETACH, command)` doesn't work, even with the `*p` version so as to be able not to enter full path to application. NB. I know that `command` is generally platform dependent, but that's not the point of my question.
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", line 21, in <module> from roi_detector import ViolaJonesRoi File "/Users/username/Downloads/headtracker_version_0.0/roi_detector.py", line 21, in <module> import opencv as cv ImportError: No module named opencv ~/Downloads/headtracker_version_0.0:. ``` Ok, looks like it's called opencv2. So I swap out occurances of import opencv as cv with ``` import cv2 as cv ``` now in viola\_jones\_opencv.py I have ``` import cv2 as cv from cv import * from cv.highgui import * ``` And I get an error on importing highgui ``` ImportError: No module named highgui ```
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", line 21, in <module> from roi_detector import ViolaJonesRoi File "/Users/username/Downloads/headtracker_version_0.0/roi_detector.py", line 21, in <module> import opencv as cv ImportError: No module named opencv ~/Downloads/headtracker_version_0.0:. ``` Ok, looks like it's called opencv2. So I swap out occurances of import opencv as cv with ``` import cv2 as cv ``` now in viola\_jones\_opencv.py I have ``` import cv2 as cv from cv import * from cv.highgui import * ``` And I get an error on importing highgui ``` ImportError: No module named highgui ```
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", line 21, in <module> from roi_detector import ViolaJonesRoi File "/Users/username/Downloads/headtracker_version_0.0/roi_detector.py", line 21, in <module> import opencv as cv ImportError: No module named opencv ~/Downloads/headtracker_version_0.0:. ``` Ok, looks like it's called opencv2. So I swap out occurances of import opencv as cv with ``` import cv2 as cv ``` now in viola\_jones\_opencv.py I have ``` import cv2 as cv from cv import * from cv.highgui import * ``` And I get an error on importing highgui ``` ImportError: No module named highgui ```
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. Otherwise, the file is left unchanged.
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", line 21, in <module> from roi_detector import ViolaJonesRoi File "/Users/username/Downloads/headtracker_version_0.0/roi_detector.py", line 21, in <module> import opencv as cv ImportError: No module named opencv ~/Downloads/headtracker_version_0.0:. ``` Ok, looks like it's called opencv2. So I swap out occurances of import opencv as cv with ``` import cv2 as cv ``` now in viola\_jones\_opencv.py I have ``` import cv2 as cv from cv import * from cv.highgui import * ``` And I get an error on importing highgui ``` ImportError: No module named highgui ```
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. Otherwise, the file is left unchanged.
``` 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", line 21, in <module> from roi_detector import ViolaJonesRoi File "/Users/username/Downloads/headtracker_version_0.0/roi_detector.py", line 21, in <module> import opencv as cv ImportError: No module named opencv ~/Downloads/headtracker_version_0.0:. ``` Ok, looks like it's called opencv2. So I swap out occurances of import opencv as cv with ``` import cv2 as cv ``` now in viola\_jones\_opencv.py I have ``` import cv2 as cv from cv import * from cv.highgui import * ``` And I get an error on importing highgui ``` ImportError: No module named highgui ```
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 when the flutter app is launched in the mobile phone?
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://stackoverflow.com/a/7027113/1367159) link might help for that. 2. Deploy the Flask based APIs somewhere. There are few free web servers available out there (e.g. MS Azure). [This](https://www.freecodecamp.org/news/how-to-build-a-web-application-using-flask-and-deploy-it-to-the-cloud-3551c985e492/) or [this](https://www.freecodecamp.org/news/how-to-host-lightweight-apps-for-free-a29773e5f39e/) link might help.
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") TypeError: 'file' object is unsubscriptable ``` <http://pastebin.com/1wMbaSYY>
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 system's authoritative database of users, which may not necessarily be `/etc/passwd`.
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") TypeError: 'file' object is unsubscriptable ``` <http://pastebin.com/1wMbaSYY>
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") TypeError: 'file' object is unsubscriptable ``` <http://pastebin.com/1wMbaSYY>
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 system's authoritative database of users, which may not necessarily be `/etc/passwd`.
``` #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) { struct passwd * p = getpwuid(i); if (p != NULL) printf("%d : %s\n", i, p->pw_name); } } ```
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") TypeError: 'file' object is unsubscriptable ``` <http://pastebin.com/1wMbaSYY>
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) { struct passwd * p = getpwuid(i); if (p != NULL) printf("%d : %s\n", i, p->pw_name); } } ```
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") TypeError: 'file' object is unsubscriptable ``` <http://pastebin.com/1wMbaSYY>
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 system's authoritative database of users, which may not necessarily be `/etc/passwd`.
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. ``` num_1 = int(input("Enter the first number: ")) num_2 = int(input("Enter the second number: ")) Total = num_1 + num_2 print("The total is: ",Total) if num_1 > num_2: print("num_1 is greater then num_2") elif num_2 > num_1: print("num_2 is greater then num_1") elif num_1 == num_2: print("Equal") else: if num_1 == str: if num_2 == str: print("invalid") ```
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 num_2 > num_1: print("num_2 is greater then num_1") else: print("Equal") ```
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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 python2 and python3 on Ubuntu 16.04 and also sets the appropriate raw1394 link. Copied from <https://github.com/chennavarri/docker-ubuntu-python-opencv> ``` FROM ubuntu:16.04 MAINTAINER Chenna Varri RUN apt-get update RUN apt-get install -y build-essential apt-utils RUN apt-get install -y cmake git libgtk2.0-dev pkg-config libavcodec-dev \ libavformat-dev libswscale-dev RUN apt-get update && apt-get install -y python-dev python-numpy \ python3 python3-pip python3-dev libtbb2 libtbb-dev \ libjpeg-dev libjasper-dev libdc1394-22-dev \ python-opencv libopencv-dev libav-tools python-pycurl \ libatlas-base-dev gfortran webp qt5-default libvtk6-dev zlib1g-dev RUN pip3 install numpy RUN apt-get install -y python-pip RUN pip install --upgrade pip RUN cd ~/ &&\ git clone https://github.com/Itseez/opencv.git &&\ git clone https://github.com/Itseez/opencv_contrib.git &&\ cd opencv && mkdir build && cd build && cmake -DWITH_QT=ON -DWITH_OPENGL=ON -DFORCE_VTK=ON -DWITH_TBB=ON -DWITH_GDAL=ON -DWITH_XINE=ON -DBUILD_EXAMPLES=ON .. && \ make -j4 && make install && ldconfig # Set the appropriate link RUN ln /dev/null /dev/raw1394 RUN cd ~/opencv ``` Some additional instructions for people newly starting with Docker: * In the directory where you put this Dockerfile, build the docker image as `docker build -t ubuntu_cv .` * Once the image is built, you can check by doing `docker images` ``` REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu_cv latest 6210ddd6346b 24 minutes ago 2.192 GB ``` * You can start a docker container as `docker run -t -i ubuntu_cv:latest`
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 install -y \ keyboard-configuration \ nvidia-driver-440\ curl \ ca-certificates \ sudo \ git \ bzip2 \ libx11-6 \ cmake \ g++ \ wget \ build-essential \ cmake \ git \ unzip \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv \ qt5-default \ libvtk6-dev \ zlib1g-dev \ libcudnn7=7.6.5.32-1+cuda10.2 \ libcudnn7-dev=7.6.5.32-1+cuda10.2 \ python3-pip \ python3-venv \ nano RUN alias python='/usr/bin/python3' RUN pip3 install numpy RUN pip3 install torch #RUN echo ############ && python --version && ############## # Install Open CV - Warning, this takes absolutely forever RUN git clone https://github.com/opencv/opencv_contrib && \ cd opencv_contrib && \ git fetch --all --tags && \ git checkout tags/4.3.0 && \ cd .. && \ git clone https://github.com/opencv/opencv.git && \ cd opencv && \ git checkout tags/4.3.0 #RUN pip3 freeze && which python3 && python3 --version ################################################################ #################### OPENCV CPU ################################ #RUN pwd &&\ # cd opencv && \ # pwd &&\ # mkdir build && cd build && \ # pwd &&\ # cmake -DCMAKE_BUILD_TYPE=Release \ # -DENABLE_CXX14=ON \ # -DBUILD_PERF_TESTS=OFF \ # -DOPENCV_GENERATE_PKGCONFIG=ON \ # -DWITH_XINE=ON \ # -DBUILD_TESTS=OFF \ # -DENABLE_PRECOMPILED_HEADERS=OFF \ # -DCMAKE_SKIP_RPATH=ON \ # -DBUILD_WITH_DEBUG_INFO=OFF \ # -DOPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \ # # -Dopencv_dnn_superres=ON /usr/bin/ .. && \ # make -j$(nproc) && \ # make install ################################################################ #################### OPENCV GPU ################################ RUN cd opencv && mkdir build && cd build && \ cmake -DCMAKE_BUILD_TYPE=Release \ -D CMAKE_CXX_COMPILER=/usr/bin/g++ \ -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) \ -D BUILD_NEW_PYTHON_SUPPORT=ON \ -D BUILD_opencv_python3=ON \ -D HAVE_opencv_python3=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-10.2 \ -D CUDA_BIN_PATH=/usr/local/cuda-10.2 \ -D CUDNN_INCLUDE_DIR=/usr/include/cudnn.h \ -D WITH_CUDNN=ON \ -D CUDA_ARCH_BIN=6.1 \ -D OPENCV_DNN_CUDA=ON \ -D WITH_CUDA=ON \ -D BUILD_opencv_cudacodec=OFF \ -D WITH_GTK=ON \ -D CMAKE_BUILD_TYPE=RELEASE \ -D CUDA_HOST_COMPILER:FILEPATH=/usr/bin/gcc-7 \ -D ENABLE_PRECOMPILED_HEADERS=OFF \ -D WITH_TBB=ON \ -D WITH_OPENMP=ON \ -D WITH_IPP=ON \ -D BUILD_EXAMPLES=OFF \ -D BUILD_DOCS=OFF \ -D BUILD_PERF_TESTS=OFF \ -D BUILD_TESTS=OFF \ -D WITH_CSTRIPES=ON \ -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \ -D CMAKE_INSTALL_PREFIX=/usr/local/ \ -DBUILD_opencv_python3=ON \ -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) \ -D PYTHON3_EXECUTABLE=$(which python3) \ -D PYTHON_INCLUDE_DIR=$(python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \ -D PYTHON3_INCLUDE_DIR=$(python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \ -D PYTHON3_LIBRARY=$(python3 -c "from distutils.sysconfig import get_config_var;from os.path import dirname,join ; print(join(dirname(get_config_var('LIBPC')),get_config_var('LDLIBRARY')))") \ -D PYTHON3_NUMPY_INCLUDE_DIRS=$(python3 -c "import numpy; print(numpy.get_include())") \ -D PYTHON3_PACKAGES_PATH=$(python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \ -D OPENCV_GENERATE_PKGCONFIG=ON .. \ -Dopencv_dnn_superres=ON /usr/bin/ .. && \ make -j$(nproc) && \ make install RUN pip3 install opencv/build/python_loader ``` then you can run ``` import torch import os print('availabe:',torch.cuda.is_available() ) print('devices available', torch.cuda.device_count()) print('device id:',torch.cuda.current_device() ) print('device address', torch.cuda.device(0)) print('gpu model',torch.cuda.get_device_name(0)) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using device:', device) #Additional Info when using cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import cv2 print("DNN_BACKEND_CUDA",cv2.dnn.DNN_BACKEND_CUDA) print("DNN_BACKEND_CUDA",cv2.dnn.DNN_TARGET_CUDA) ``` and you will get something like: ``` Using device: cuda availabe: True devices available 1 device id: 0 device address <torch.cuda.device object at 0x7f5a0a392550> gpu model GeForce GTX 1050 Ti Memory Usage: Allocated: 0.0 GB Cached: 0.0 GB DNN_BACKEND_CUDA 5 DNN_BACKEND_CUDA 6 ```
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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 using Python 2 so my entire Dockerfile to get OpenCvv installed is just: ``` FROM continuumio/anaconda EXPOSE 5000 ADD . /code-directory WORKDIR code-directory RUN conda install opencv CMD ["python", "run-code.py"] ``` This will install Anaconda from the continuumio/anaconda Dockerfile and then it will use Anaconda to install opencv. There is a seperate continuumio Dockerfile for Python 3 if you need that as well.
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 libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev apt install -y qt5-default apt install -y libatlas-base-dev apt install -y libfaac-dev libmp3lame-dev libtheora-dev apt install -y libvorbis-dev libxvidcore-dev apt install -y libopencore-amrnb-dev libopencore-amrwb-dev apt install -y x264 x265 v4l-utils apt install -y libprotobuf-dev protobuf-compiler apt install -y libeigen3-dev wget --output-document cv.zip https://github.com/opencv/opencv/archive/4.0.1.zip wget --output-document contrib.zip https://github.com/opencv/opencv_contrib/archive/4.0.1.zip unzip cv.zip unzip contrib.zip cd opencv-4.0.1 mkdir build cd build cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D WITH_TBB=ON \ -D WITH_V4L=ON \ -D WITH_QT=ON \ -D WITH_OPENGL=ON \ -D WITH_CUDA=ON \ -D WITH_NVCUVID=OFF \ -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.0.1/modules \ -D OPENCV_ENABLE_NONFREE=ON \ .. make -j 'number of gpu' make install ldconfig ln -s /usr/local/lib/python3.6/dist-packages/cv2/python-3.6/cv2.cpython-36m-x86_64-linux-gnu.so /usr/local/lib/python3.6/dist-packages/cv2/python-3.6/cv2.so ``` This works for me!!
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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 COPY . . CMD [ "python", "./camera_controller.py" ] ``` With this line in requirements.txt ``` opencv-python-headless==<your version> ```
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 \ wget \ unzip \ yasm \ pkg-config \ libswscale-dev \ libtbb2 \ libtbb-dev \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libopenjp2-7-dev \ libavformat-dev \ libpq-dev \ && pip install numpy \ && wget -q https://github.com/opencv/opencv/archive/${OPENCV_VERSION}.zip -O opencv.zip \ && unzip -qq opencv.zip -d /opt \ && rm -rf opencv.zip \ && cmake \ -D BUILD_TIFF=ON \ -D BUILD_opencv_java=OFF \ -D WITH_CUDA=OFF \ -D WITH_OPENGL=ON \ -D WITH_OPENCL=ON \ -D WITH_IPP=ON \ -D WITH_TBB=ON \ -D WITH_EIGEN=ON \ -D WITH_V4L=ON \ -D BUILD_TESTS=OFF \ -D BUILD_PERF_TESTS=OFF \ -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=$(python3.9 -c "import sys; print(sys.prefix)") \ -D PYTHON_EXECUTABLE=$(which python3.9) \ -D PYTHON_INCLUDE_DIR=$(python3.9 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \ -D PYTHON_PACKAGES_PATH=$(python3.9 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \ /opt/opencv-${OPENCV_VERSION} \ && make -j$(nproc) \ && make install \ && rm -rf /opt/build/* \ && rm -rf /opt/opencv-${OPENCV_VERSION} \ && rm -rf /var/lib/apt/lists/* \ && apt-get -qq autoremove \ && apt-get -qq clean ```
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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 using Python 2 so my entire Dockerfile to get OpenCvv installed is just: ``` FROM continuumio/anaconda EXPOSE 5000 ADD . /code-directory WORKDIR code-directory RUN conda install opencv CMD ["python", "run-code.py"] ``` This will install Anaconda from the continuumio/anaconda Dockerfile and then it will use Anaconda to install opencv. There is a seperate continuumio Dockerfile for Python 3 if you need that as well.
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 \ wget \ unzip \ yasm \ pkg-config \ libswscale-dev \ libtbb2 \ libtbb-dev \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libopenjp2-7-dev \ libavformat-dev \ libpq-dev \ && pip install numpy \ && wget -q https://github.com/opencv/opencv/archive/${OPENCV_VERSION}.zip -O opencv.zip \ && unzip -qq opencv.zip -d /opt \ && rm -rf opencv.zip \ && cmake \ -D BUILD_TIFF=ON \ -D BUILD_opencv_java=OFF \ -D WITH_CUDA=OFF \ -D WITH_OPENGL=ON \ -D WITH_OPENCL=ON \ -D WITH_IPP=ON \ -D WITH_TBB=ON \ -D WITH_EIGEN=ON \ -D WITH_V4L=ON \ -D BUILD_TESTS=OFF \ -D BUILD_PERF_TESTS=OFF \ -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=$(python3.9 -c "import sys; print(sys.prefix)") \ -D PYTHON_EXECUTABLE=$(which python3.9) \ -D PYTHON_INCLUDE_DIR=$(python3.9 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \ -D PYTHON_PACKAGES_PATH=$(python3.9 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \ /opt/opencv-${OPENCV_VERSION} \ && make -j$(nproc) \ && make install \ && rm -rf /opt/build/* \ && rm -rf /opt/opencv-${OPENCV_VERSION} \ && rm -rf /var/lib/apt/lists/* \ && apt-get -qq autoremove \ && apt-get -qq clean ```
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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 python2 and python3 on Ubuntu 16.04 and also sets the appropriate raw1394 link. Copied from <https://github.com/chennavarri/docker-ubuntu-python-opencv> ``` FROM ubuntu:16.04 MAINTAINER Chenna Varri RUN apt-get update RUN apt-get install -y build-essential apt-utils RUN apt-get install -y cmake git libgtk2.0-dev pkg-config libavcodec-dev \ libavformat-dev libswscale-dev RUN apt-get update && apt-get install -y python-dev python-numpy \ python3 python3-pip python3-dev libtbb2 libtbb-dev \ libjpeg-dev libjasper-dev libdc1394-22-dev \ python-opencv libopencv-dev libav-tools python-pycurl \ libatlas-base-dev gfortran webp qt5-default libvtk6-dev zlib1g-dev RUN pip3 install numpy RUN apt-get install -y python-pip RUN pip install --upgrade pip RUN cd ~/ &&\ git clone https://github.com/Itseez/opencv.git &&\ git clone https://github.com/Itseez/opencv_contrib.git &&\ cd opencv && mkdir build && cd build && cmake -DWITH_QT=ON -DWITH_OPENGL=ON -DFORCE_VTK=ON -DWITH_TBB=ON -DWITH_GDAL=ON -DWITH_XINE=ON -DBUILD_EXAMPLES=ON .. && \ make -j4 && make install && ldconfig # Set the appropriate link RUN ln /dev/null /dev/raw1394 RUN cd ~/opencv ``` Some additional instructions for people newly starting with Docker: * In the directory where you put this Dockerfile, build the docker image as `docker build -t ubuntu_cv .` * Once the image is built, you can check by doing `docker images` ``` REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu_cv latest 6210ddd6346b 24 minutes ago 2.192 GB ``` * You can start a docker container as `docker run -t -i ubuntu_cv:latest`
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 \ wget \ unzip \ yasm \ pkg-config \ libswscale-dev \ libtbb2 \ libtbb-dev \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libopenjp2-7-dev \ libavformat-dev \ libpq-dev \ && pip install numpy \ && wget -q https://github.com/opencv/opencv/archive/${OPENCV_VERSION}.zip -O opencv.zip \ && unzip -qq opencv.zip -d /opt \ && rm -rf opencv.zip \ && cmake \ -D BUILD_TIFF=ON \ -D BUILD_opencv_java=OFF \ -D WITH_CUDA=OFF \ -D WITH_OPENGL=ON \ -D WITH_OPENCL=ON \ -D WITH_IPP=ON \ -D WITH_TBB=ON \ -D WITH_EIGEN=ON \ -D WITH_V4L=ON \ -D BUILD_TESTS=OFF \ -D BUILD_PERF_TESTS=OFF \ -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=$(python3.9 -c "import sys; print(sys.prefix)") \ -D PYTHON_EXECUTABLE=$(which python3.9) \ -D PYTHON_INCLUDE_DIR=$(python3.9 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \ -D PYTHON_PACKAGES_PATH=$(python3.9 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \ /opt/opencv-${OPENCV_VERSION} \ && make -j$(nproc) \ && make install \ && rm -rf /opt/build/* \ && rm -rf /opt/opencv-${OPENCV_VERSION} \ && rm -rf /var/lib/apt/lists/* \ && apt-get -qq autoremove \ && apt-get -qq clean ```
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv \ qt5-default \ libvtk6-dev \ zlib1g-dev # Install Open CV - Warning, this takes absolutely forever RUN mkdir -p ~/opencv cd ~/opencv && \ wget https://github.com/opencv/opencv/archive/3.0.0.zip && \ unzip 3.0.0.zip && \ rm 3.0.0.zip && \ mv opencv-3.0.0 OpenCV && \ cd OpenCV && \ mkdir build && \ cd build && \ cmake \ -DWITH_QT=ON \ -DWITH_OPENGL=ON \ -DFORCE_VTK=ON \ -DWITH_TBB=ON \ -DWITH_GDAL=ON \ -DWITH_XINE=ON \ -DBUILD_EXAMPLES=ON .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ```
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 install -y \ keyboard-configuration \ nvidia-driver-440\ curl \ ca-certificates \ sudo \ git \ bzip2 \ libx11-6 \ cmake \ g++ \ wget \ build-essential \ cmake \ git \ unzip \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv \ qt5-default \ libvtk6-dev \ zlib1g-dev \ libcudnn7=7.6.5.32-1+cuda10.2 \ libcudnn7-dev=7.6.5.32-1+cuda10.2 \ python3-pip \ python3-venv \ nano RUN alias python='/usr/bin/python3' RUN pip3 install numpy RUN pip3 install torch #RUN echo ############ && python --version && ############## # Install Open CV - Warning, this takes absolutely forever RUN git clone https://github.com/opencv/opencv_contrib && \ cd opencv_contrib && \ git fetch --all --tags && \ git checkout tags/4.3.0 && \ cd .. && \ git clone https://github.com/opencv/opencv.git && \ cd opencv && \ git checkout tags/4.3.0 #RUN pip3 freeze && which python3 && python3 --version ################################################################ #################### OPENCV CPU ################################ #RUN pwd &&\ # cd opencv && \ # pwd &&\ # mkdir build && cd build && \ # pwd &&\ # cmake -DCMAKE_BUILD_TYPE=Release \ # -DENABLE_CXX14=ON \ # -DBUILD_PERF_TESTS=OFF \ # -DOPENCV_GENERATE_PKGCONFIG=ON \ # -DWITH_XINE=ON \ # -DBUILD_TESTS=OFF \ # -DENABLE_PRECOMPILED_HEADERS=OFF \ # -DCMAKE_SKIP_RPATH=ON \ # -DBUILD_WITH_DEBUG_INFO=OFF \ # -DOPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \ # # -Dopencv_dnn_superres=ON /usr/bin/ .. && \ # make -j$(nproc) && \ # make install ################################################################ #################### OPENCV GPU ################################ RUN cd opencv && mkdir build && cd build && \ cmake -DCMAKE_BUILD_TYPE=Release \ -D CMAKE_CXX_COMPILER=/usr/bin/g++ \ -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) \ -D BUILD_NEW_PYTHON_SUPPORT=ON \ -D BUILD_opencv_python3=ON \ -D HAVE_opencv_python3=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-10.2 \ -D CUDA_BIN_PATH=/usr/local/cuda-10.2 \ -D CUDNN_INCLUDE_DIR=/usr/include/cudnn.h \ -D WITH_CUDNN=ON \ -D CUDA_ARCH_BIN=6.1 \ -D OPENCV_DNN_CUDA=ON \ -D WITH_CUDA=ON \ -D BUILD_opencv_cudacodec=OFF \ -D WITH_GTK=ON \ -D CMAKE_BUILD_TYPE=RELEASE \ -D CUDA_HOST_COMPILER:FILEPATH=/usr/bin/gcc-7 \ -D ENABLE_PRECOMPILED_HEADERS=OFF \ -D WITH_TBB=ON \ -D WITH_OPENMP=ON \ -D WITH_IPP=ON \ -D BUILD_EXAMPLES=OFF \ -D BUILD_DOCS=OFF \ -D BUILD_PERF_TESTS=OFF \ -D BUILD_TESTS=OFF \ -D WITH_CSTRIPES=ON \ -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \ -D CMAKE_INSTALL_PREFIX=/usr/local/ \ -DBUILD_opencv_python3=ON \ -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) \ -D PYTHON3_EXECUTABLE=$(which python3) \ -D PYTHON_INCLUDE_DIR=$(python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \ -D PYTHON3_INCLUDE_DIR=$(python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \ -D PYTHON3_LIBRARY=$(python3 -c "from distutils.sysconfig import get_config_var;from os.path import dirname,join ; print(join(dirname(get_config_var('LIBPC')),get_config_var('LDLIBRARY')))") \ -D PYTHON3_NUMPY_INCLUDE_DIRS=$(python3 -c "import numpy; print(numpy.get_include())") \ -D PYTHON3_PACKAGES_PATH=$(python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \ -D OPENCV_GENERATE_PKGCONFIG=ON .. \ -Dopencv_dnn_superres=ON /usr/bin/ .. && \ make -j$(nproc) && \ make install RUN pip3 install opencv/build/python_loader ``` then you can run ``` import torch import os print('availabe:',torch.cuda.is_available() ) print('devices available', torch.cuda.device_count()) print('device id:',torch.cuda.current_device() ) print('device address', torch.cuda.device(0)) print('gpu model',torch.cuda.get_device_name(0)) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using device:', device) #Additional Info when using cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') import cv2 print("DNN_BACKEND_CUDA",cv2.dnn.DNN_BACKEND_CUDA) print("DNN_BACKEND_CUDA",cv2.dnn.DNN_TARGET_CUDA) ``` and you will get something like: ``` Using device: cuda availabe: True devices available 1 device id: 0 device address <torch.cuda.device object at 0x7f5a0a392550> gpu model GeForce GTX 1050 Ti Memory Usage: Allocated: 0.0 GB Cached: 0.0 GB DNN_BACKEND_CUDA 5 DNN_BACKEND_CUDA 6 ```
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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 apt-get install -y -q build-essential run apt-get install -y -q cmake run apt-get install -y -q python2.7 python2.7-dev run wget 'https://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg' && /bin/sh setuptools-0.6c11-py2.7.egg && rm -f setuptools-0.6c11-py2.7.egg run curl 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py' | python2.7 run pip install numpy run apt-get install -y -q libavformat-dev libavcodec-dev libavfilter-dev libswscale-dev run apt-get install -y -q libjpeg-dev libpng-dev libtiff-dev libjasper-dev zlib1g-dev libopenexr-dev libxine-dev libeigen3-dev libtbb-dev add build_opencv.sh /build_opencv.sh run /bin/sh /build_opencv.sh run rm -rf /build_opencv.sh ```
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 \ wget \ unzip \ yasm \ pkg-config \ libswscale-dev \ libtbb2 \ libtbb-dev \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libopenjp2-7-dev \ libavformat-dev \ libpq-dev \ && pip install numpy \ && wget -q https://github.com/opencv/opencv/archive/${OPENCV_VERSION}.zip -O opencv.zip \ && unzip -qq opencv.zip -d /opt \ && rm -rf opencv.zip \ && cmake \ -D BUILD_TIFF=ON \ -D BUILD_opencv_java=OFF \ -D WITH_CUDA=OFF \ -D WITH_OPENGL=ON \ -D WITH_OPENCL=ON \ -D WITH_IPP=ON \ -D WITH_TBB=ON \ -D WITH_EIGEN=ON \ -D WITH_V4L=ON \ -D BUILD_TESTS=OFF \ -D BUILD_PERF_TESTS=OFF \ -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=$(python3.9 -c "import sys; print(sys.prefix)") \ -D PYTHON_EXECUTABLE=$(which python3.9) \ -D PYTHON_INCLUDE_DIR=$(python3.9 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \ -D PYTHON_PACKAGES_PATH=$(python3.9 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \ /opt/opencv-${OPENCV_VERSION} \ && make -j$(nproc) \ && make install \ && rm -rf /opt/build/* \ && rm -rf /opt/opencv-${OPENCV_VERSION} \ && rm -rf /var/lib/apt/lists/* \ && apt-get -qq autoremove \ && apt-get -qq clean ```
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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 using Python 2 so my entire Dockerfile to get OpenCvv installed is just: ``` FROM continuumio/anaconda EXPOSE 5000 ADD . /code-directory WORKDIR code-directory RUN conda install opencv CMD ["python", "run-code.py"] ``` This will install Anaconda from the continuumio/anaconda Dockerfile and then it will use Anaconda to install opencv. There is a seperate continuumio Dockerfile for Python 3 if you need that as well.
``` 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 apt-get install -y -q build-essential run apt-get install -y -q cmake run apt-get install -y -q python2.7 python2.7-dev run wget 'https://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg' && /bin/sh setuptools-0.6c11-py2.7.egg && rm -f setuptools-0.6c11-py2.7.egg run curl 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py' | python2.7 run pip install numpy run apt-get install -y -q libavformat-dev libavcodec-dev libavfilter-dev libswscale-dev run apt-get install -y -q libjpeg-dev libpng-dev libtiff-dev libjasper-dev zlib1g-dev libopenexr-dev libxine-dev libeigen3-dev libtbb-dev add build_opencv.sh /build_opencv.sh run /bin/sh /build_opencv.sh run rm -rf /build_opencv.sh ```
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv \ qt5-default \ libvtk6-dev \ zlib1g-dev # Install Open CV - Warning, this takes absolutely forever RUN mkdir -p ~/opencv cd ~/opencv && \ wget https://github.com/opencv/opencv/archive/3.0.0.zip && \ unzip 3.0.0.zip && \ rm 3.0.0.zip && \ mv opencv-3.0.0 OpenCV && \ cd OpenCV && \ mkdir build && \ cd build && \ cmake \ -DWITH_QT=ON \ -DWITH_OPENGL=ON \ -DFORCE_VTK=ON \ -DWITH_TBB=ON \ -DWITH_GDAL=ON \ -DWITH_XINE=ON \ -DBUILD_EXAMPLES=ON .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ```
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 using Python 2 so my entire Dockerfile to get OpenCvv installed is just: ``` FROM continuumio/anaconda EXPOSE 5000 ADD . /code-directory WORKDIR code-directory RUN conda install opencv CMD ["python", "run-code.py"] ``` This will install Anaconda from the continuumio/anaconda Dockerfile and then it will use Anaconda to install opencv. There is a seperate continuumio Dockerfile for Python 3 if you need that as well.
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 -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 \ pkg-config \ python-dev \ python-opencv \ libopencv-dev \ libav-tools \ libjpeg-dev \ libpng-dev \ libtiff-dev \ libjasper-dev \ libgtk2.0-dev \ python-numpy \ python-pycurl \ libatlas-base-dev \ gfortran \ webp \ python-opencv # Install Open CV - Warning, this takes absolutely forever RUN cd ~ && git clone https://github.com/Itseez/opencv.git && \ cd opencv && \ git checkout 3.0.0 && \ cd ~ && git clone https://github.com/Itseez/opencv_contrib.git && \ cd opencv_contrib && \ git checkout 3.0.0 && \ cd ~/opencv && mkdir -p build && cd build && \ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF .. && \ make -j4 && \ make install && \ ldconfig COPY requirements.txt /usr/src/app/ RUN pip install --no-cache-dir -r requirements.txt COPY . /usr/src/app ``` And my requirements.txt file ``` Flask==0.8 gunicorn==0.14.2 requests==0.11.1 bs4==0.0.1 nltk==3.2.1 pymysql==0.7.2 xlsxwriter==0.8.5 numpy==1.11 Pillow==3.2.0 cv2==1.0 pytesseract==0.1 ```
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 python2 and python3 on Ubuntu 16.04 and also sets the appropriate raw1394 link. Copied from <https://github.com/chennavarri/docker-ubuntu-python-opencv> ``` FROM ubuntu:16.04 MAINTAINER Chenna Varri RUN apt-get update RUN apt-get install -y build-essential apt-utils RUN apt-get install -y cmake git libgtk2.0-dev pkg-config libavcodec-dev \ libavformat-dev libswscale-dev RUN apt-get update && apt-get install -y python-dev python-numpy \ python3 python3-pip python3-dev libtbb2 libtbb-dev \ libjpeg-dev libjasper-dev libdc1394-22-dev \ python-opencv libopencv-dev libav-tools python-pycurl \ libatlas-base-dev gfortran webp qt5-default libvtk6-dev zlib1g-dev RUN pip3 install numpy RUN apt-get install -y python-pip RUN pip install --upgrade pip RUN cd ~/ &&\ git clone https://github.com/Itseez/opencv.git &&\ git clone https://github.com/Itseez/opencv_contrib.git &&\ cd opencv && mkdir build && cd build && cmake -DWITH_QT=ON -DWITH_OPENGL=ON -DFORCE_VTK=ON -DWITH_TBB=ON -DWITH_GDAL=ON -DWITH_XINE=ON -DBUILD_EXAMPLES=ON .. && \ make -j4 && make install && ldconfig # Set the appropriate link RUN ln /dev/null /dev/raw1394 RUN cd ~/opencv ``` Some additional instructions for people newly starting with Docker: * In the directory where you put this Dockerfile, build the docker image as `docker build -t ubuntu_cv .` * Once the image is built, you can check by doing `docker images` ``` REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu_cv latest 6210ddd6346b 24 minutes ago 2.192 GB ``` * You can start a docker container as `docker run -t -i ubuntu_cv:latest`
``` 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 apt-get install -y -q build-essential run apt-get install -y -q cmake run apt-get install -y -q python2.7 python2.7-dev run wget 'https://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg' && /bin/sh setuptools-0.6c11-py2.7.egg && rm -f setuptools-0.6c11-py2.7.egg run curl 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py' | python2.7 run pip install numpy run apt-get install -y -q libavformat-dev libavcodec-dev libavfilter-dev libswscale-dev run apt-get install -y -q libjpeg-dev libpng-dev libtiff-dev libjasper-dev zlib1g-dev libopenexr-dev libxine-dev libeigen3-dev libtbb-dev add build_opencv.sh /build_opencv.sh run /bin/sh /build_opencv.sh run rm -rf /build_opencv.sh ```
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': [313], 'col2': [5]} df = pd.DataFrame(data=d,dtype=np.int16) print(df.dtypes) #col1 int16 #col2 int16 #dtype: object df['col1'] *= 1000000 df['col2'] *= 10000 print(df.dtypes) #col1 int32 #col2 int16 #dtype: object ``` As you can see, since the upper limit of int16 is 32767, the result of both 313\*1000000 and 5\*10000 would exceed the upper limit. However, it seems like pandas only automatically converted the result of the first calculation to int32 (which makes sense and is ideal for me) but still kept the result of the second calculation as int16 (which made the result wierd and not ideal for me). Is there a way to always make pandas automatically convert the numeric type when needed?
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': [313], 'col2': [5]} df = pd.DataFrame(data=d,dtype=np.int16) print(df.dtypes) #col1 int16 #col2 int16 #dtype: object df['col1'] *= 1000000 df['col2'] *= 10000 print(df.dtypes) #col1 int32 #col2 int16 #dtype: object ``` As you can see, since the upper limit of int16 is 32767, the result of both 313\*1000000 and 5\*10000 would exceed the upper limit. However, it seems like pandas only automatically converted the result of the first calculation to int32 (which makes sense and is ideal for me) but still kept the result of the second calculation as int16 (which made the result wierd and not ideal for me). Is there a way to always make pandas automatically convert the numeric type when needed?
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': [313], 'col2': [5]} df = pd.DataFrame(data=d,dtype=np.int16) print(df.dtypes) #col1 int16 #col2 int16 #dtype: object df['col1'] *= 1000000 df['col2'] *= 10000 print(df.dtypes) #col1 int32 #col2 int16 #dtype: object ``` As you can see, since the upper limit of int16 is 32767, the result of both 313\*1000000 and 5\*10000 would exceed the upper limit. However, it seems like pandas only automatically converted the result of the first calculation to int32 (which makes sense and is ideal for me) but still kept the result of the second calculation as int16 (which made the result wierd and not ideal for me). Is there a way to always make pandas automatically convert the numeric type when needed?
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. ``` sentence = input(": ") def count_vowels_recursive(sentence): total = 0 if sentence[0] == "a" or sentence[0] == "e" or sentence[0] == "i" or sentence[0] == "o" or sentence[0] == "u": total = total + 1 + count_vowels_recursive(sentence[1:]) else: total = total + count_vowels_recursive(sentence[1:]) return the_sum print(count_vowels_recursive(sentence)) ``` Here are my previous two solutions. ``` def count_vowels(sentence): a = sentence.count("a") b = sentence.count("e") c = sentence.count("i") d = sentence.count("o") e = sentence.count("i") return (a+b+c+d+e) def count_vowels_iterative(sentence): a_ = 0 e_ = 0 i_ = 0 o_ = 0 u_ = 0 for i in range(len(sentence)): if "a" == sentence[i]: a_ = a_ + 1 elif "e" == sentence[i]: e_ = e_ + 1 elif "i" == sentence[i]: i_ = i_ + 1 elif "o" == sentence[i]: o_ = o_ + 1 elif "u" == sentence[i]: u_ = u_ + 1 else: continue return (a_ + e_ + i_ + o_ + u_) ```
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:]) # the boolean expression `sentence[0] in "aeiou"` is cast to an int for the addition ```
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. ``` sentence = input(": ") def count_vowels_recursive(sentence): total = 0 if sentence[0] == "a" or sentence[0] == "e" or sentence[0] == "i" or sentence[0] == "o" or sentence[0] == "u": total = total + 1 + count_vowels_recursive(sentence[1:]) else: total = total + count_vowels_recursive(sentence[1:]) return the_sum print(count_vowels_recursive(sentence)) ``` Here are my previous two solutions. ``` def count_vowels(sentence): a = sentence.count("a") b = sentence.count("e") c = sentence.count("i") d = sentence.count("o") e = sentence.count("i") return (a+b+c+d+e) def count_vowels_iterative(sentence): a_ = 0 e_ = 0 i_ = 0 o_ = 0 u_ = 0 for i in range(len(sentence)): if "a" == sentence[i]: a_ = a_ + 1 elif "e" == sentence[i]: e_ = e_ + 1 elif "i" == sentence[i]: i_ = i_ + 1 elif "o" == sentence[i]: o_ = o_ + 1 elif "u" == sentence[i]: u_ = u_ + 1 else: continue return (a_ + e_ + i_ + o_ + u_) ```
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', 'back': 'direction', 'go': 'verb', 'stop': 'verb', 'kill': 'verb', 'eat': 'verb', 'the': 'stop', 'in': 'stop', 'of': 'stop', 'from': 'stop', 'at': 'stop', 'it': 'stop', 'door': 'noun', 'bear': 'noun', 'princess': 'noun', 'cabinet': 'noun'} ``` But I can't find anything on the internet that's helped me do so. How would I go about turning this into a list? Help is appreciated!
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', 'direction', 'noun', 'stop', 'direction', 'noun', 'direction', 'direction', 'stop', 'noun', 'stop', 'stop', 'direction', 'stop', 'verb', 'verb', 'direction', 'direction', 'stop', 'verb', 'verb'] ``` You could use `.items()` to get the key,value pairs as a list of tuples ``` >>> list(lexicon.items()) [('princess', 'noun'), ('down', 'direction'), ('east', 'direction'), ('north', 'direction'), ('cabinet', 'noun'), ('at', 'stop'), ('right', 'direction'), ('door', 'noun'), ('left', 'direction'), ('up', 'direction'), ('from', 'stop'), ('bear', 'noun'), ('of', 'stop'), ('the', 'stop'), ('south', 'direction'), ('in', 'stop'), ('kill', 'verb'), ('eat', 'verb'), ('back', 'direction'), ('west', 'direction'), ('it', 'stop'), ('go', 'verb'), ('stop', 'verb')] ```
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', 'stop'), ('in', 'stop'), ('go', 'verb'), ('door', 'noun'), ('from', 'stop'), ('west', 'direction'), ('eat', 'verb'), ('east', 'direction'), ('north', 'direction'), ('stop', 'verb'), ('bear', 'noun'), ('back', 'direction'), ('cabinet', 'noun'), ('princess', 'noun'), ('of', 'stop'), ('up', 'direction'), ('the', 'stop'), ('south', 'direction'), ('left', 'direction')] ``` hope this helps
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 = [ {'name':'a1', 'level':0}, {'name':'a2', 'level':0}, {'name':'a3', 'level':1}, {'name':'a4', 'level':1}, {'name':'a5', 'level':2}, {'name':'a6', 'level':2}, ] the_result = myFunction(obj, temp_obj) print(temp_obj) #above print would result to an empty list #this is my problem #end of main body ------------- def myFunction(obj, new_temp_obj): inside_list = [] for x in obj[:]: if x['level'] == 0: inside_list.append(x) obj.remove(x) #removing the element that was added to the inside_list new_temp_obj = obj[:] #copying the remaining element print(new_temp_obj) # the above print would result to #[{'name': 'a3', 'level': 1}, {'name': 'a4', 'level': 1}, {'name': 'a5', 'level': 2}, {'name': 'a6', 'level': 2}] return inside_list ``` Am I missing something or did I misunderstand the idea of python call by reference?
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, click the Events button and then create or select a handler for any event and/or jump to it in code view. When in code view, you can use the drop-down lists at the top to select the form or a control/component or any field declared `WithEvents` and to create and/or jump to the handler for that event.
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: name, version: version, operating_system: os, sources: - source: news target: industry - source: testing target: computer ``` I need a help specially on Sources part that how I can add my dictionary list there
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') as f: yaml.dump(tmp_data, f) ``` Contents from the yaml: ```yaml services: name: testyaml os: Linux sources: - source: news target: industry - source: testing target: computer version: '2.5' ```
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 row +=1 wbk.save('pyt.xls') Result obtained: 1 2 3 4 2 3 4 5 Desired result row1: 1 2 3 4 row2: 2 3 4 5 ``` Any ideas on how to get the desired result? thanks
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 enumerate(c): sheet.write(row,col,d) ```
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 Python 3 (in Windows 7 RC1). When I ran the TurtleWorld module from Swampy, I got error messages about the print and exec statements, which are now functions in Python 3. I fixed those errors by including parentheses with print and exec in the code of the GUI and World modules. I also got an error that the Tkinter module could not be found. It turned out that in Python 3, the module name is spelled with a lower case t. The third error is more difficult: ImportError: No module named tkFont. Does anyone have any idea, please? Thank you.
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 > existing third party software is > compatible with Python 2 than Python 3 > right now. > > >
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 Python 3 (in Windows 7 RC1). When I ran the TurtleWorld module from Swampy, I got error messages about the print and exec statements, which are now functions in Python 3. I fixed those errors by including parentheses with print and exec in the code of the GUI and World modules. I also got an error that the Tkinter module could not be found. It turned out that in Python 3, the module name is spelled with a lower case t. The third error is more difficult: ImportError: No module named tkFont. Does anyone have any idea, please? Thank you.
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 > existing third party software is > compatible with Python 2 than Python 3 > right now. > > >
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 Python 2 (I used 2.7.5). * Then download the Swampy-2.1.1.tar.gz file from here: <https://pypi.python.org/pypi/swampy/2.1.1>. Extract this file by double-clicking on it in your Downloads folder. * Open the resulting folder, Swampy 2.1.1. You should see several items, including the folder, swampy. * Here's the key step: Drag this folder to the last one in this path: Macintosh HD/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages. TO REPEAT: drag the folder "swampy" and drop it into the "site-packages" folder. * Once you do that, fire up Python in the terminal and type "import swampy.TurtleWorld." If you see the chevrons (>>>) and you don't see an error message, you're good to continue the lessons.
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 Python 3 (in Windows 7 RC1). When I ran the TurtleWorld module from Swampy, I got error messages about the print and exec statements, which are now functions in Python 3. I fixed those errors by including parentheses with print and exec in the code of the GUI and World modules. I also got an error that the Tkinter module could not be found. It turned out that in Python 3, the module name is spelled with a lower case t. The third error is more difficult: ImportError: No module named tkFont. Does anyone have any idea, please? Thank you.
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 World", font=('Helvetica', 24,)) custom_font_serif = ('Times', 24, 'bold') butt02 = tkinter.Button(top, text="Hello World", font=custom_font_serif) custom_font_sans = ('Helvetica', 36, 'italic') butt03 = tkinter.Button(top, text="Hello World", font=custom_font_sans) butt01.pack() butt02.pack() butt03.pack() top.mainloop() ```
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 Python 3 (in Windows 7 RC1). When I ran the TurtleWorld module from Swampy, I got error messages about the print and exec statements, which are now functions in Python 3. I fixed those errors by including parentheses with print and exec in the code of the GUI and World modules. I also got an error that the Tkinter module could not be found. It turned out that in Python 3, the module name is spelled with a lower case t. The third error is more difficult: ImportError: No module named tkFont. Does anyone have any idea, please? Thank you.
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 Python 2 (I used 2.7.5). * Then download the Swampy-2.1.1.tar.gz file from here: <https://pypi.python.org/pypi/swampy/2.1.1>. Extract this file by double-clicking on it in your Downloads folder. * Open the resulting folder, Swampy 2.1.1. You should see several items, including the folder, swampy. * Here's the key step: Drag this folder to the last one in this path: Macintosh HD/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages. TO REPEAT: drag the folder "swampy" and drop it into the "site-packages" folder. * Once you do that, fire up Python in the terminal and type "import swampy.TurtleWorld." If you see the chevrons (>>>) and you don't see an error message, you're good to continue the lessons.
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 Python 3 (in Windows 7 RC1). When I ran the TurtleWorld module from Swampy, I got error messages about the print and exec statements, which are now functions in Python 3. I fixed those errors by including parentheses with print and exec in the code of the GUI and World modules. I also got an error that the Tkinter module could not be found. It turned out that in Python 3, the module name is spelled with a lower case t. The third error is more difficult: ImportError: No module named tkFont. Does anyone have any idea, please? Thank you.
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 World", font=('Helvetica', 24,)) custom_font_serif = ('Times', 24, 'bold') butt02 = tkinter.Button(top, text="Hello World", font=custom_font_serif) custom_font_sans = ('Helvetica', 36, 'italic') butt03 = tkinter.Button(top, text="Hello World", font=custom_font_sans) butt01.pack() butt02.pack() butt03.pack() top.mainloop() ```
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 Python 2 (I used 2.7.5). * Then download the Swampy-2.1.1.tar.gz file from here: <https://pypi.python.org/pypi/swampy/2.1.1>. Extract this file by double-clicking on it in your Downloads folder. * Open the resulting folder, Swampy 2.1.1. You should see several items, including the folder, swampy. * Here's the key step: Drag this folder to the last one in this path: Macintosh HD/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages. TO REPEAT: drag the folder "swampy" and drop it into the "site-packages" folder. * Once you do that, fire up Python in the terminal and type "import swampy.TurtleWorld." If you see the chevrons (>>>) and you don't see an error message, you're good to continue the lessons.
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 to -123 with 456 in the most efficient way possible. ``` updated_example_string = "456 456 456 456 456 456 -123 456 -123 456 -123 456..." ``` I know that python's regular expression library has a sub method that will replace matching values quite efficiently. Is there a way to replace values that DO NOT match? As I mentioned, this is a rather large string, coming from a source file around 100MB. Assuming there's a way to use re.sub to accomplish this task, is that even the correct/most efficient way of handling such problem?
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 turn all those numbers into 456. The `\g<1>` in the replacement preserves any space captured by the first group. [Demo on regex101](https://regex101.com/r/9Hu5wu/1) In Python: ``` import re string = "102.3 42.89 -1234 98 -812.7 374 5 -123 8 -123 13 -123 21 -123" print re.sub(r'(^|\s)(?!-123(\s|$))-?[0-9.]+(?=\s|$)', '\g<1>456', string) ``` Output ``` 456 456 456 456 456 456 456 -123 456 -123 456 -123 456 -123 ``` [Demo on rextester](https://rextester.com/RIGDMV75452)
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 character * `-?` Optional `-` * `\d+(?:\.\d+)?` Match 1+ digits with an optional part that matches a `.` and 1+ digits * `(?!\S)` Negative lookahead to assert what is on the right is not a non-whitespace character Example ``` import re pattern = r"(?<!\S)-?\d+(?:\.\d+)?(?!\S)" s = "102.3 42.89 98 812.7 374 5 -123 8 -123 13 -123 21" print(re.sub(pattern, lambda m: "456" if m.group() != "-123" else m.group(), s)) ``` Result ``` 456 456 456 456 456 456 -123 456 -123 456 -123 456 ``` See the [Regex demo](https://regex101.com/r/aReSQ7/1) | [Python demo](https://ideone.com/5JQSTf)
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_ubuntu_test /root/docker_test.sh", "epsilon":"PT15M", "executor":"/var/lib/mesos/executors/docker" }' | http POST localhost:8080/scheduler/iso8601 ``` I also configured logging in executor and below are the logs I get when it fails ``` Feb 11 13:51:36 ip6-localhost docker[13895]: Ready to serve! Feb 11 13:51:36 ip6-localhost docker[13895]: Registered with Mesos slave Feb 11 13:51:36 ip6-localhost docker[13895]: Task is: ct:1392126755612:2:testing_docker_executor Feb 11 13:51:36 ip6-localhost docker[13895]: JSON from framework is rubbish Feb 11 13:51:36 ip6-localhost docker[13895]: No JSON object could be decoded Feb 11 13:51:36 ip6-localhost docker[13895]: Traceback (most recent call last): Feb 11 13:51:36 ip6-localhost docker[13895]: File "/var/lib/mesos/executors/docker", line 120, in launchTask Feb 11 13:51:36 ip6-localhost docker[13895]: self.data = json.loads(task.data) if task.data else {} Feb 11 13:51:36 ip6-localhost docker[13895]: File "/usr/lib/python2.7/json/__init__.py", line 338, in loads Feb 11 13:51:36 ip6-localhost docker[13895]: return _default_decoder.decode(s) Feb 11 13:51:36 ip6-localhost docker[13895]: File "/usr/lib/python2.7/json/decoder.py", line 365, in decode Feb 11 13:51:36 ip6-localhost docker[13895]: obj, end = self.raw_decode(s, idx=_w(s, 0).end()) Feb 11 13:51:36 ip6-localhost docker[13895]: File "/usr/lib/python2.7/json/decoder.py", line 383, in raw_decode Feb 11 13:51:36 ip6-localhost docker[13895]: raise ValueError("No JSON object could be decoded") Feb 11 13:51:36 ip6-localhost docker[13895]: ValueError: No JSON object could be decoded Feb 11 13:51:36 ip6-localhost docker[13895]: [] Feb 11 13:51:36 ip6-localhost docker[13895]: Traceback (most recent call last): Feb 11 13:51:36 ip6-localhost docker[13895]: File "/var/lib/mesos/executors/docker", line 67, in run Feb 11 13:51:36 ip6-localhost docker[13895]: img = self.args[0] Feb 11 13:51:36 ip6-localhost docker[13895]: IndexError: list index out of range ``` Is there something I am missing. Do I need to provide JSON in command.
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 trying to convert **numpy array** to **list** getting this problem with value like ***0.7999999999999999*** in place of ***0.8*** please help me to convert **numpy array** to normal python **list** without losing the **decimal value.**
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/en/stable/interactive/python-ipython-diff.html#magics) for further information. Some constructs you can use in IPython do not exist in Python, and you get an error if you try to run them as Python commands, as stated in IPython guide: > > Unless expressed otherwise all of the construct you will see here will raise a SyntaxError if run in a pure Python shell, or if executing in a Python script. > > > This because IPython is a set of tools aimed at improving the experience of using Python interactively, easing some repetitive tasks.
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/abcAdminUtil -abort -streamId ETL_' \ 'SystemManagement_PA@Fact_SCOPE_OVPAGlobal' proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (output, err) = proc.communicate() # Storing Output in output variable ``` Value of output variable when running from shell: ``` Abort cmd output:PID:8717 Executing abort function hibernateConfigurationFile = /OBRHA/HPE-OBR/PMDB/lib/hibernate-core-4.3.8.Final.jar Starting to Abort Stream ETL_SystemManagement_PA@Fact_SCOPE_OVPAGlobal Aborting StreamETL_SystemManagement_PA@Fact_SCOPE_OVPAGlobal ``` Value of output variable when running from cron: ``` PID:830 ``` It seems output after creating new process is not being stored inside variable , i don't know why ?
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 import Image import numpy as np image1 = Image.open("E:\\python\\downloaded\\captcha.png").convert('L') image2 = Image.open("E:\\python\\downloaded\\captcha.png").convert('L') pix = image1.load() for column in range(0, image1.height): for row in range(0, image1.width): if pix[row, column] >= 90: pix[row, column] = 255 cv2.imshow("1", np.array(image2)) cv2.imshow("2", np.array(image1)) cv2.waitKey(0) ``` But I am trying to remove the line crossing the text, but it does not seem to work. I tried with below portion of code which is posted on other question in StackOverflow. But it does not work [![enter image description here](https://i.stack.imgur.com/b9iNk.jpg)](https://i.stack.imgur.com/b9iNk.jpg) ``` def eliminate_zeros(self,vector): return [(dex,v) for (dex,v) in enumerate(vector) if v!=0 ] def get_line_position(self,img): sumx=img.sum(axis=0) list_without_zeros=self.eliminate_zeros(sumx) min1,min2=heapq.nsmallest(2,list_without_zeros,key=itemgetter(1)) l=[dex for [dex,val] in enumerate(sumx) if val==min1[1] or val==min2[1]] mindex=[l[0],l[len(l)-1]] cols=img[:,mindex[:]] col1=cols[:,0] col2=cols[:,1] col1_without_0=self.eliminate_zeros(col1) col2_without_0=self.eliminate_zeros(col2) line_length=len(col1_without_0) dex1=col1_without_0[round(len(col1_without_0)/2)][0] dex2=col2_without_0[round(len(col2_without_0)/2)][0] p1=[dex1,mindex[0]] p2=[dex2,mindex[1]] return p1,p2,line_length def remove_line(self,p1,p2,LL,img): m=(p2[0]-p1[0])/(p2[1]-p1[1]) if p2[1]!=p1[1] else np.inf w,h=len(img),len(img[0]) x=list(range(h)) y=list(map(lambda z : int(np.round(p1[0]+m*(z-p1[1]))),x)) img_removed_line=list(img) for dex in range(h): i,j=y[dex],x[dex] i=int(i) j=int(j) rlist=[] while i>=0 and i<len(img_removed_line)-1: f1=i if img_removed_line[i][j]==0 and img_removed_line[i-1][j]==0: break rlist.append(i) i=i-1 i,j=y[dex],x[dex] i=int(i) j=int(j) while i>=0 and i<len(img_removed_line)-1: f2=i if img_removed_line[i][j]==0 and img_removed_line[i+1][j]==0: break rlist.append(i) i=i+1 if np.abs(f2-f1) in [LL+1,LL,LL-1]: rlist=list(set(rlist)) for k in rlist: img_removed_line[k][j]=0 return img_removed_line ``` I am new to CV and can someone help here to suggest the way?. Original and partially processed image files are attached here.
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 import cv2 import numpy as np image = cv2.imread('captcha.png') image = cv2.blur(image, (3, 3)) ret, image = cv2.threshold(image, 90, 255, cv2.THRESH_BINARY) image = cv2.dilate(image, np.ones((3, 1), np.uint8)) image = cv2.erode(image, np.ones((2, 2), np.uint8)) cv2.imshow("1", np.array(image)) cv2.waitKey(0) ```
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_not(masked_img) kernel = np.ones((5,5),np.uint8) dilation = cv2.dilate(masked_img_inv,kernel,iterations = 3) ret,thresh2 = cv2.threshold(dilation,254,255,cv2.THRESH_BINARY_INV) thresh2=cv2.bitwise_not(thresh2) cv2.waitKey(0) cv2.destroyAllWindows() ```
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 recommend?
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 text more semantically by using N-Grams ( <http://en.wikipedia.org/wiki/N-gram> ).
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 recommend?
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). Ignoring the "longest common" strangeness, and defining "percent difference" as the edit distance between the strings divided by the max length (times 100 of course;-), what about: ``` def levenshtein_distance(first, second): """Find the Levenshtein distance between two strings.""" if len(first) > len(second): first, second = second, first if len(second) == 0: return len(first) first_length = len(first) + 1 second_length = len(second) + 1 distance_matrix = [[0] * second_length for x in range(first_length)] for i in range(first_length): distance_matrix[i][0] = i for j in range(second_length): distance_matrix[0][j]=j for i in xrange(1, first_length): for j in range(1, second_length): deletion = distance_matrix[i-1][j] + 1 insertion = distance_matrix[i][j-1] + 1 substitution = distance_matrix[i-1][j-1] if first[i-1] != second[j-1]: substitution += 1 distance_matrix[i][j] = min(insertion, deletion, substitution) return distance_matrix[first_length-1][second_length-1] def percent_diff(first, second): return 100*levenshtein_distance(a, b) / float(max(len(a), len(b))) a = "the quick brown fox" b = "the quick vrown fox" print '%.2f' % percent_diff(a, b) ``` The Levenshtein function is from [Stavros' blog](http://www.korokithakis.net/node/87). The result in this case would be 5.26 (percent difference).
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 recommend?
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 recommend?
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). Ignoring the "longest common" strangeness, and defining "percent difference" as the edit distance between the strings divided by the max length (times 100 of course;-), what about: ``` def levenshtein_distance(first, second): """Find the Levenshtein distance between two strings.""" if len(first) > len(second): first, second = second, first if len(second) == 0: return len(first) first_length = len(first) + 1 second_length = len(second) + 1 distance_matrix = [[0] * second_length for x in range(first_length)] for i in range(first_length): distance_matrix[i][0] = i for j in range(second_length): distance_matrix[0][j]=j for i in xrange(1, first_length): for j in range(1, second_length): deletion = distance_matrix[i-1][j] + 1 insertion = distance_matrix[i][j-1] + 1 substitution = distance_matrix[i-1][j-1] if first[i-1] != second[j-1]: substitution += 1 distance_matrix[i][j] = min(insertion, deletion, substitution) return distance_matrix[first_length-1][second_length-1] def percent_diff(first, second): return 100*levenshtein_distance(a, b) / float(max(len(a), len(b))) a = "the quick brown fox" b = "the quick vrown fox" print '%.2f' % percent_diff(a, b) ``` The Levenshtein function is from [Stavros' blog](http://www.korokithakis.net/node/87). The result in this case would be 5.26 (percent difference).
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 text more semantically by using N-Grams ( <http://en.wikipedia.org/wiki/N-gram> ).
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 recommend?
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 text more semantically by using N-Grams ( <http://en.wikipedia.org/wiki/N-gram> ).
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 recommend?
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). Ignoring the "longest common" strangeness, and defining "percent difference" as the edit distance between the strings divided by the max length (times 100 of course;-), what about: ``` def levenshtein_distance(first, second): """Find the Levenshtein distance between two strings.""" if len(first) > len(second): first, second = second, first if len(second) == 0: return len(first) first_length = len(first) + 1 second_length = len(second) + 1 distance_matrix = [[0] * second_length for x in range(first_length)] for i in range(first_length): distance_matrix[i][0] = i for j in range(second_length): distance_matrix[0][j]=j for i in xrange(1, first_length): for j in range(1, second_length): deletion = distance_matrix[i-1][j] + 1 insertion = distance_matrix[i][j-1] + 1 substitution = distance_matrix[i-1][j-1] if first[i-1] != second[j-1]: substitution += 1 distance_matrix[i][j] = min(insertion, deletion, substitution) return distance_matrix[first_length-1][second_length-1] def percent_diff(first, second): return 100*levenshtein_distance(a, b) / float(max(len(a), len(b))) a = "the quick brown fox" b = "the quick vrown fox" print '%.2f' % percent_diff(a, b) ``` The Levenshtein function is from [Stavros' blog](http://www.korokithakis.net/node/87). The result in this case would be 5.26 (percent difference).
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:root:While running > ['third\_party/tools/depot\_tools/third\_party/gsutil/gsutil', 'cp', > 'gs://arc-build/naclports/builds/pepper\_40/python.zip', > '/tmp/tmpUZ0IoK/naclports-python'] ERROR:root:GSResponseError: > status=403, code=None, reason=Forbidden. > > > ERROR:root:Try prodaccess, and if it does not solve the problem try rm > ~/.devstore\_token @@@STEP\_WARNINGS@@@ ERROR:root:Retrying after 9 s > sleeping Traceback (most recent call last): File > "/home/fkiller/arc/src/build/build\_common.py", line 938, in wrapper > return func(\*args, \*\*kwargs) File "/home/fkiller/arc/src/build/util/download\_package\_util.py", line 243, > in \_download\_package\_with\_retries > self.\_download\_method(url, download\_package\_path) File "/home/fkiller/arc/src/build/util/download\_package\_util.py", line 119, > in \_download > build\_common.get\_gsutil\_executable(), 'cp', url, destination\_path]) File > "/home/fkiller/arc/src/build/util/download\_package\_util.py", line 97, > in execute\_subprocess > output = subprocess.check\_output(cmd, cwd=cwd, stderr=subprocess.STDOUT) File "/usr/lib/python2.7/subprocess.py", > line 573, in check\_output > raise CalledProcessError(retcode, cmd, output=output) CalledProcessError: Command > '['third\_party/tools/depot\_tools/third\_party/gsutil/gsutil', 'cp', > 'gs://arc-build/naclports/builds/pepper\_40/python.zip', > '/tmp/tmpUZ0IoK/naclports-python']' returned non-zero exit status 1 > > > Any idea to resolve this without changing build script? I may manually pointing python.zip from other sources such as <https://naclports.storage.googleapis.com/builds/pepper_40/trunk-147-g49eb4c9/publish/python/pnacl/python.zip>, but I want to build it as is without changing scripts. I've already tried to setup gsutil and its authenticator, but it didn't fix the issue. **EDIT:** After @elijah-taylor fixed ACL, now I'm getting errors below > > Traceback (most recent call last): File "src/build/configure.py", > line 365, in > sys.exit(main()) File "src/build/configure.py", line 347, in main > \_gclient\_sync\_third\_party() File "src/build/configure.py", line 132, in \_gclient\_sync\_third\_party > subprocess.check\_output(cmd, cwd=os.path.dirname(gclient\_filename)) File > "/usr/lib/python2.7/subprocess.py", line 566, in check\_output > process = Popen(stdout=PIPE, \*popenargs, \*\*kwargs) File "/usr/lib/python2.7/subprocess.py", line 710, in **init** > errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1327, in \_execute\_child > raise child\_exception OSError: [Errno 2] No such file or directory > > > In the line 132, ``` File "src/build/configure.py", line 132, in _gclient_sync_third_party subprocess.check_output(cmd, cwd=os.path.dirname(gclient_filename)) ``` gclient\_filename is "third\_party/.gclient" and os.path.dirname(gclient\_filename) is "thrid\_party".
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 {count}') # Do some io related stuff logger.info(f'finished processing for thing {count}') def process_things_concurrently(things) with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for count, thing in enumerate(things): futures.append(executor.submit(process_thing, thing, count)) for future in concurrent.futures.as_completed(futures): future.result() ``` As the code is now, the logging can happen in any order. For example: ``` starting processing for thing 2 starting processing for thing 1 finished processing for thing 2 finished processing for thing 1 ``` I want to change the code so that the records for a particular call of `process_thing()` are buffered until the future finishes. In other words, all of the records for a particular call stick together. These 'groups' of records are ordered by when the call finished. So from the example above the log output above would instead look like ``` starting processing for thing 2 finished processing for thing 2 starting processing for thing 1 finished processing for thing 1 ``` what I've tried --------------- I tried making a logger for each call that would have its own custom handler, possibly subclassing [BufferingHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.BufferingHandler). But eventually there will be lots of "things" and I read that making a lot of loggers is bad. I'm open to anything that works! Thanks.
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 = logger self._call_stack = [] # list of (method, *args, **kwargs) tuples self._delayed_methods = { name : partial(self._delayed_method_proxy, getattr(logger, name)) for name in ["info", "debug", "warning", "error", "critical"] } def __getattr__(self, name): """ Proxy getattr to self.logger, except for self._delayed_methods. """ return self._delayed_methods.get(name, getattr(self.logger, name)) def _delayed_method_proxy(self, method, *args, **kwargs): self._call_stack.append((method, args, kwargs)) def flush(self): """ Flush self._call_stack to the real logger. """ for method, args, kwargs in self._call_stack: method(*args, **kwargs) self._call_stack = [] ``` In your example, you could use it like so: ``` import logging logger = logging.getLogger(__name__) def process_thing(thing, count): dlogger = DelayedLogger(logger) dlogger.info(f'starting processing for thing {count}') # Do some io related stuff dlogger.info(f'finished processing for thing {count}') dlogger.flush() process_thing(None, 10) ``` There may be ways to beautfiy this or make it more compact, but it should get the job done if that's what you really want.
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._delayed_methods = { name: partial(self._delayed_method_proxy, getattr(logger, name)) for name in ["info", "debug", "warning", "error", "critical"] } def __getattr__(self, name): """ Proxy getattr to self.logger, except for self._delayed_methods. """ return self._delayed_methods.get(name, getattr(self.logger, name)) def _delayed_method_proxy(self, method, *args, **kwargs): self._call_stack.append((method, args, kwargs)) def flush(self): """ Flush self._call_stack to the real logger. """ for method, args, kwargs in self._call_stack: method(*args, **kwargs) self._call_stack = [] def __init__(self, logger): self.logger = logger self._thread_loggers: typing.Dict[self.ThreadLogger] = {} def new_thread(self, count): """Make a new sub-logger class that writes to the call stack in its slot""" new_logger = self.ThreadLogger(self.logger) self._thread_loggers[count] = new_logger return new_logger def get_thread(self, count): return self._thread_loggers[count] delayed_logger = DelayedLogger(logger) ``` Which can be used like this ``` delayed_logger = DelayedLogger(logger) with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for count, thing in enumerate(things): futures.append(executor.submit(process_thing, count, thing, logger=delayed_logger.new_thread(count))) for future in concurrent.futures.as_completed(futures): count = future.result() delayed_logger.get_thread(count).flush() ``` The problem here is that `process_thing()` now needs to take the logger as an argument and the logger is limited in scope. If `process_thing()` calls subroutines then the their logging won't be delayed. Probably the solution is just to not try to do this at all. Instead threads can make a log filter or some other way to distinguish their messages.
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([[1,2],[3,4]],columns=['a','b']) foo.apply(lambda x: [np.min(x)/2,np.max(x)/2], axis='index') ``` code will return: ``` a b 0 min(a)/2 min(b)/2 1 max(a)/2 max(b)/2 ``` ### Q2 - For some reason I would like to output a `pandaq.Series` of arrays instead: ``` 0 [min(a)/2, max(a)/2] 1 [min(b)/2, max(b)/2] ... ``` I have tried `reduce=True` without success. Then, **How should I do?** Thank you in advance.
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([[1,2],[3,4]],columns=['a','b']) foo.apply(lambda x: [np.min(x)/2,np.max(x)/2], axis='index') ``` code will return: ``` a b 0 min(a)/2 min(b)/2 1 max(a)/2 max(b)/2 ``` ### Q2 - For some reason I would like to output a `pandaq.Series` of arrays instead: ``` 0 [min(a)/2, max(a)/2] 1 [min(b)/2, max(b)/2] ... ``` I have tried `reduce=True` without success. Then, **How should I do?** Thank you in advance.
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, trans_desc, trans_amnt) VALUES(" + datetime.datetime.strptime('{0}', '%d/%m/%Y').strftime('%Y-%m-%d') + ",{2},{3}), row)" cur.execute(insertionSQL) ``` I get the following error from my python script: ``` (data_string, format)) ValueError: time data '{0}' does not match format '%d/%m/%Y' ```
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 handle position](https://i.stack.imgur.com/pVl4s.png)](https://i.stack.imgur.com/pVl4s.png) κ (kappa) is defined in paper.js as `Numerical.KAPPA` (more on Kappa [*here*](http://www.whizkidtech.redprince.net/bezier/circle/kappa/)). The code to change the radius could look like this ([*Click here for the Sketch*](http://sketch.paperjs.org/#S/fVRdb5tAEPwrJ57AwQSSuJHiuFJSqVKVpLXsvoU8nGENp8BhHUsSN/F/790B8fHR8oDY2d2ZuQH73eI0B+vKWj8DRqnlWlERqzrkIX+hggiIkCwIh1eypJh6K1lTnmRga6hgHO3A910ib46r59bsD5jYue/MQ66IvG2VZfs1ZPIZYkmLooJ5K1Ui7CQWzOtyByICjjQBCfp6alvxCFnBScG/C+nbhhc54ZB32URj/mShydQOloDfCsFBrGjMqtJWPlyD3FFDbEtsY/8rmfnk48O0cE38RofIS1udLMg00BqHkB86/sZEVXwuEUXFY8aTZU2tORVjD5dHflBx54zbM5lkXdA32x9SqHQlQ4jt+7pVA6WkaGW9jUbqOaLHtC810iU7la+MTI7aRzrvlcX6AEckBZak6Bi0KeVxBvfAE0wVea0yIT+rHASLaObd3SyXN81Gfc8aow1pAngPW7Qdt27joP272H12xaC7Up4++5tB/7ZALHLb6XjQnx8kncxknctE2tRU+9F/8nbqk/fe5KRGzk0kIyfNmXtLdS6/qu5ijf7gGpya2ZnrFwPNSxMRZDqieTGqednT/Jdk0Ars280vJrIZlQwMcnPv6GP/H8mzgeTMRHA02bM+e7vYMdJPVv9U5T/dRgB91hKldfX4dPgL)): ``` var rect = new Path.Rectangle(new Point(100, 100), new Size(100, 100), 30); rect.fullySelected = true; var step = 1; var percentage = 0; function onFrame(event) { percentage += step; setCornerRadius(rect, percentage) if (percentage > 50 || percentage < 0) { step *= -1; } } function setCornerRadius(rectPath, roundingPercent) { roundingPercent = Math.min(50, Math.max(0, roundingPercent)); var rectBounds = rectPath.bounds; var radius = roundingPercent/100 * Math.min(rectBounds.width, rectBounds.height); var handleLength = radius * Numerical.KAPPA; l = rectBounds.getLeft(), t = rectBounds.getTop(), r = rectBounds.getRight(), b = rectBounds.getBottom(); var segs = rectPath.segments; segs[0].point.x = segs[3].point.x = l + radius; segs[0].handleOut.x = segs[3].handleIn.x = -handleLength; segs[4].point.x = segs[7].point.x = r - radius; segs[4].handleOut.x = segs[7].handleIn.x = handleLength; segs[1].point.y = segs[6].point.y = b - radius; segs[1].handleIn.y = segs[6].handleOut.y = handleLength; segs[2].point.y = segs[5].point.y = t + radius; segs[2].handleOut.y = segs[5].handleIn.y = -handleLength; } ``` ***Edit:*** I just found a much easier way using a shape. Not sure which approach performs faster. Here is the implementation using a `Shape` ([*Click here for the Sketch*](http://sketch.paperjs.org/#S/VVHBTsMwDP0VK6dklNIJ7bJRLkjckBA7Eg6h9daoW1Kl3kBs/XectIcuJ/v5+fnZuQhnjijWYtsiVY3IROXrmJ9NgN7+IZSwLIqNdhEIWBEDDn9g25gO8w8GjNsfUEbsNnv31pHk5iwqqGxsY0kZdbOkrhh+LBTLR+m8p+BbfPEHH3iMFgFrLbg4Tu8Ju2hnMtNhqNCR2UePRWLtTq4i6x149xp4L4lnZii4cJFu+PBmqMmP1skV+xsT8ys5ntHu0kgV7WlKBoOp7ann/nSaxZz8MN1Jk92BnBWeS1gVcL3OyU/seLIF/NJmixLul0lg0G6I6/BvfAc0bRcv2Yv159fwDw==)). ``` var size = 100; var rect = new Shape.Rectangle(new Rectangle(new Point(100, 100), new Size(size, size)), 30); rect.strokeColor = "red"; var step = 1; var percentage = 0; function onFrame(event) { percentage = Math.min(50, Math.max(0, percentage + step)); rect.radius = size * percentage / 100; if (percentage >= 50 || percentage <= 0) { step *= -1; } } ```
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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.8333333333333334, 3615]] from pprint import pprint from collections import Counter, defaultdict c = Counter(i[2] for i in l) d = defaultdict(lambda: defaultdict(int)) for i in l: if c[i[2]] > 1: d[i[2]][i[0]] += 1 rv = [] for k, v in d.items(): rv.append({'id': k, 'No_matched_skills': len(v), 'skills': [*v]}) pprint(rv, width=10) ``` Output: ``` [{'No_matched_skills': 3, 'id': 54, 'skills': ['laravel', 'php', 'python']}, {'No_matched_skills': 2, 'id': 3615, 'skills': ['laravel', 'python']}] ```
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_dict = {} for l in my_list: compute_dict.setdefault(l[2], []) compute_dict[l[2]].append(l[0]) final_list = [] for k,v in compute_dict.items(): final_list.append({"id":k,"No_matched_skills":len(set(v)),"skills":", ".join(set(v))}) ``` Basically, the first step is to create a dictionary with IDs as keys and programming language as values. Therefore, `compute_dict` will look like ``` >>> {54: ['laravel', 'php', 'python', 'laravel'], 3615: ['laravel','python'], 1405: ['php'], 5175: ['php'], 5176: ['php'], 5252: ['php'], 5279: ['php']} ``` So, from there were able to create a list with the expected output. Note that I'm using `set()` in order to remove duplicates from the original dict.
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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.8333333333333334, 3615]] from pprint import pprint from collections import Counter, defaultdict c = Counter(i[2] for i in l) d = defaultdict(lambda: defaultdict(int)) for i in l: if c[i[2]] > 1: d[i[2]][i[0]] += 1 rv = [] for k, v in d.items(): rv.append({'id': k, 'No_matched_skills': len(v), 'skills': [*v]}) pprint(rv, width=10) ``` Output: ``` [{'No_matched_skills': 3, 'id': 54, 'skills': ['laravel', 'php', 'python']}, {'No_matched_skills': 2, 'id': 3615, 'skills': ['laravel', 'python']}] ```
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 groupby and convert to dictionary res = df.groupby('id', as_index=False)['skills'].agg(funcs).to_dict('records') print(res) [{'No_matched_skills': 3, 'id': 54, 'skills': 'laravel, php, python'}, {'No_matched_skills': 1, 'id': 1405, 'skills': 'php'}, {'No_matched_skills': 2, 'id': 3615, 'skills': 'laravel, python'}, {'No_matched_skills': 1, 'id': 5175, 'skills': 'php'}, {'No_matched_skills': 1, 'id': 5176, 'skills': 'php'}, {'No_matched_skills': 1, 'id': 5252, 'skills': 'php'}, {'No_matched_skills': 1, 'id': 5279, 'skills': 'php'}] ```
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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.8333333333333334, 3615]] for i in skillList: d[i[2]].add(i[0]) temp = [ {'id':i,'No_matched_skills':len(d[i]),'skills':','.join(d[i])} for i in d if len(d[i])>1] print temp ``` This will remove repetitions and only show those which have more than one skill Output: ``` [{'skills': 'laravel,python,php', 'No_matched_skills': 3, 'id': 54}, {'skills': 'laravel,python', 'No_matched_skills': 2, 'id': 3615}] ```
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, 3615]] new_list = [[a, list(b)] for a, b in itertools.groupby(sorted(_list, key=lambda x:x[-1]), key=lambda x:x[-1])] final_result = [{'id':a, 'No_matched_skills':len(b), 'skills':[c for c, *_ in b]} for a, b in new_list] filtered = list(filter(lambda x:x['No_matched_skills'] > 1, final_result)) ``` Output: ``` [{'id': 54, 'No_matched_skills': 4, 'skills': ['laravel', 'php', 'python', 'laravel']}, {'id': 3615, 'No_matched_skills': 2, 'skills': ['laravel', 'python']}] ```
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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', 0.8333333333333334, 54], ['python',0.8333333333333334, 3615]] o = [] for key, grp in groupby(sorted(l, key=itemgetter(2)), key=itemgetter(2)): skills = [l[0] for l in grp] o.append({"id": key, "no_matched_skills": len(skills), "skills": skills}) o ``` Output: ``` [{'id': 54, 'no_matched_skills': 4, 'skills': ['laravel', 'php', 'python', 'laravel']}, {'id': 1405, 'no_matched_skills': 1, 'skills': ['php']}, {'id': 3615, 'no_matched_skills': 2, 'skills': ['laravel', 'python']}, {'id': 5175, 'no_matched_skills': 1, 'skills': ['php']}, {'id': 5176, 'no_matched_skills': 1, 'skills': ['php']}, {'id': 5252, 'no_matched_skills': 1, 'skills': ['php']}, {'id': 5279, 'no_matched_skills': 1, 'skills': ['php']}] ```
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, 3615]] new_list = [[a, list(b)] for a, b in itertools.groupby(sorted(_list, key=lambda x:x[-1]), key=lambda x:x[-1])] final_result = [{'id':a, 'No_matched_skills':len(b), 'skills':[c for c, *_ in b]} for a, b in new_list] filtered = list(filter(lambda x:x['No_matched_skills'] > 1, final_result)) ``` Output: ``` [{'id': 54, 'No_matched_skills': 4, 'skills': ['laravel', 'php', 'python', 'laravel']}, {'id': 3615, 'No_matched_skills': 2, 'skills': ['laravel', 'python']}] ```
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.8333333333333334, 3615]] skills = {} for l in lists: skill, _, id = l if id in skills: skills[id].append(skill) else: skills[id] = [skill] output = [] for k in skills.keys(): output.append({ "id": k, "No_matched_skills": len(skills[k]), "skills": ",".join(skills[k]) }) print(output) ``` Let's look at this line by line: ``` skills = {} ``` Create a new dictionary so that for each unique ID in the `lists` variable, we can store a list of skills. ``` for l in lists: skill, _, id = l if id in skills: skills[id].append(skill) else: skills[id] = [skill] ``` Not sure what that middle variable is so I used `_` as its variable name. Change as needed. I'm using the line `skill, _, id = l` to unpack the list `l` into those variables. If I find the current `id` in the `skills` dictionary, I just go ahead and use `list.append()` to add it to the existing list. Otherwise, I create new list in place with the current skill. ``` output = [] for k in skills.keys(): output.append({ "id": k, "No_matched_skills": len(skills[k]), "skills": ",".join(skills[k]) }) ``` For each key in the `skills` dictionary, I append a dictionary to the `output` list. The `id` is simply the key, `No_matched_skills` is the size of the list for that key, and I use `",".join(skills[k])` to take that list and save it as a comma-separated string.
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, 3615]] new_list = [[a, list(b)] for a, b in itertools.groupby(sorted(_list, key=lambda x:x[-1]), key=lambda x:x[-1])] final_result = [{'id':a, 'No_matched_skills':len(b), 'skills':[c for c, *_ in b]} for a, b in new_list] filtered = list(filter(lambda x:x['No_matched_skills'] > 1, final_result)) ``` Output: ``` [{'id': 54, 'No_matched_skills': 4, 'skills': ['laravel', 'php', 'python', 'laravel']}, {'id': 3615, 'No_matched_skills': 2, 'skills': ['laravel', 'python']}] ```
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.8333333333333334, 3615]] skills = {} for l in lists: skill, _, id = l if id in skills: skills[id].append(skill) else: skills[id] = [skill] output = [] for k in skills.keys(): output.append({ "id": k, "No_matched_skills": len(skills[k]), "skills": ",".join(skills[k]) }) print(output) ``` Let's look at this line by line: ``` skills = {} ``` Create a new dictionary so that for each unique ID in the `lists` variable, we can store a list of skills. ``` for l in lists: skill, _, id = l if id in skills: skills[id].append(skill) else: skills[id] = [skill] ``` Not sure what that middle variable is so I used `_` as its variable name. Change as needed. I'm using the line `skill, _, id = l` to unpack the list `l` into those variables. If I find the current `id` in the `skills` dictionary, I just go ahead and use `list.append()` to add it to the existing list. Otherwise, I create new list in place with the current skill. ``` output = [] for k in skills.keys(): output.append({ "id": k, "No_matched_skills": len(skills[k]), "skills": ",".join(skills[k]) }) ``` For each key in the `skills` dictionary, I append a dictionary to the `output` list. The `id` is simply the key, `No_matched_skills` is the size of the list for that key, and I use `",".join(skills[k])` to take that list and save it as a comma-separated string.
``` 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.8333333333333334, 3615]] for i in skillList: d[i[2]].add(i[0]) temp = [ {'id':i,'No_matched_skills':len(d[i]),'skills':','.join(d[i])} for i in d if len(d[i])>1] print temp ``` This will remove repetitions and only show those which have more than one skill Output: ``` [{'skills': 'laravel,python,php', 'No_matched_skills': 3, 'id': 54}, {'skills': 'laravel,python', 'No_matched_skills': 2, 'id': 3615}] ```
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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.8333333333333334, 3615]] from pprint import pprint from collections import Counter, defaultdict c = Counter(i[2] for i in l) d = defaultdict(lambda: defaultdict(int)) for i in l: if c[i[2]] > 1: d[i[2]][i[0]] += 1 rv = [] for k, v in d.items(): rv.append({'id': k, 'No_matched_skills': len(v), 'skills': [*v]}) pprint(rv, width=10) ``` Output: ``` [{'No_matched_skills': 3, 'id': 54, 'skills': ['laravel', 'php', 'python']}, {'No_matched_skills': 2, 'id': 3615, 'skills': ['laravel', 'python']}] ```
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, 3615]] new_list = [[a, list(b)] for a, b in itertools.groupby(sorted(_list, key=lambda x:x[-1]), key=lambda x:x[-1])] final_result = [{'id':a, 'No_matched_skills':len(b), 'skills':[c for c, *_ in b]} for a, b in new_list] filtered = list(filter(lambda x:x['No_matched_skills'] > 1, final_result)) ``` Output: ``` [{'id': 54, 'No_matched_skills': 4, 'skills': ['laravel', 'php', 'python', 'laravel']}, {'id': 3615, 'No_matched_skills': 2, 'skills': ['laravel', 'python']}] ```
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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, 5252], ['php', 1.0, 5279], ['python', 1.0, 54], ['laravel', 0.8333333333333334, 54], ['python',0.8333333333333334, 3615]] skills = {} for l in lists: skill, _, id = l if id in skills: skills[id].append(skill) else: skills[id] = [skill] output = [] for k in skills.keys(): output.append({ "id": k, "No_matched_skills": len(skills[k]), "skills": ",".join(skills[k]) }) print(output) ``` Let's look at this line by line: ``` skills = {} ``` Create a new dictionary so that for each unique ID in the `lists` variable, we can store a list of skills. ``` for l in lists: skill, _, id = l if id in skills: skills[id].append(skill) else: skills[id] = [skill] ``` Not sure what that middle variable is so I used `_` as its variable name. Change as needed. I'm using the line `skill, _, id = l` to unpack the list `l` into those variables. If I find the current `id` in the `skills` dictionary, I just go ahead and use `list.append()` to add it to the existing list. Otherwise, I create new list in place with the current skill. ``` output = [] for k in skills.keys(): output.append({ "id": k, "No_matched_skills": len(skills[k]), "skills": ",".join(skills[k]) }) ``` For each key in the `skills` dictionary, I append a dictionary to the `output` list. The `id` is simply the key, `No_matched_skills` is the size of the list for that key, and I use `",".join(skills[k])` to take that list and save it as a comma-separated string.
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_dict = {} for l in my_list: compute_dict.setdefault(l[2], []) compute_dict[l[2]].append(l[0]) final_list = [] for k,v in compute_dict.items(): final_list.append({"id":k,"No_matched_skills":len(set(v)),"skills":", ".join(set(v))}) ``` Basically, the first step is to create a dictionary with IDs as keys and programming language as values. Therefore, `compute_dict` will look like ``` >>> {54: ['laravel', 'php', 'python', 'laravel'], 3615: ['laravel','python'], 1405: ['php'], 5175: ['php'], 5176: ['php'], 5252: ['php'], 5279: ['php']} ``` So, from there were able to create a list with the expected output. Note that I'm using `set()` in order to remove duplicates from the original dict.
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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.8333333333333334, 3615]] for i in skillList: d[i[2]].add(i[0]) temp = [ {'id':i,'No_matched_skills':len(d[i]),'skills':','.join(d[i])} for i in d if len(d[i])>1] print temp ``` This will remove repetitions and only show those which have more than one skill Output: ``` [{'skills': 'laravel,python,php', 'No_matched_skills': 3, 'id': 54}, {'skills': 'laravel,python', 'No_matched_skills': 2, 'id': 3615}] ```
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 groupby and convert to dictionary res = df.groupby('id', as_index=False)['skills'].agg(funcs).to_dict('records') print(res) [{'No_matched_skills': 3, 'id': 54, 'skills': 'laravel, php, python'}, {'No_matched_skills': 1, 'id': 1405, 'skills': 'php'}, {'No_matched_skills': 2, 'id': 3615, 'skills': 'laravel, python'}, {'No_matched_skills': 1, 'id': 5175, 'skills': 'php'}, {'No_matched_skills': 1, 'id': 5176, 'skills': 'php'}, {'No_matched_skills': 1, 'id': 5252, 'skills': 'php'}, {'No_matched_skills': 1, 'id': 5279, 'skills': 'php'}] ```
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.8333333333333334, 54], ['python',0.8333333333333334, 3615]] ``` we can see ID 54 have 3 skills (laravel,python,php) and 3615 have 2 skills Now, My Desire output as below: ``` [{ id :54 No_matched_skills: 3 skills: laravel,python,php }, { id : 3615 No_matched_skills : 2 skills: laravel,python }] ``` Can anyone please tell me how can I do?
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', 0.8333333333333334, 54], ['python',0.8333333333333334, 3615]] o = [] for key, grp in groupby(sorted(l, key=itemgetter(2)), key=itemgetter(2)): skills = [l[0] for l in grp] o.append({"id": key, "no_matched_skills": len(skills), "skills": skills}) o ``` Output: ``` [{'id': 54, 'no_matched_skills': 4, 'skills': ['laravel', 'php', 'python', 'laravel']}, {'id': 1405, 'no_matched_skills': 1, 'skills': ['php']}, {'id': 3615, 'no_matched_skills': 2, 'skills': ['laravel', 'python']}, {'id': 5175, 'no_matched_skills': 1, 'skills': ['php']}, {'id': 5176, 'no_matched_skills': 1, 'skills': ['php']}, {'id': 5252, 'no_matched_skills': 1, 'skills': ['php']}, {'id': 5279, 'no_matched_skills': 1, 'skills': ['php']}] ```
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_dict = {} for l in my_list: compute_dict.setdefault(l[2], []) compute_dict[l[2]].append(l[0]) final_list = [] for k,v in compute_dict.items(): final_list.append({"id":k,"No_matched_skills":len(set(v)),"skills":", ".join(set(v))}) ``` Basically, the first step is to create a dictionary with IDs as keys and programming language as values. Therefore, `compute_dict` will look like ``` >>> {54: ['laravel', 'php', 'python', 'laravel'], 3615: ['laravel','python'], 1405: ['php'], 5175: ['php'], 5176: ['php'], 5252: ['php'], 5279: ['php']} ``` So, from there were able to create a list with the expected output. Note that I'm using `set()` in order to remove duplicates from the original dict.
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 `Elements` if their `id` is equal to obtain this list: ```py l = [Element(1, 300), Element(2, 1), Element(3, 8)] ``` What is the most pythonic way to do this?
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 def __repr__(self): # kudos @mesejo return "Element({}, {})".format(self.id, self.value) l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)] l.sort(key=attrgetter('id')) # if it is already sorted by 'id', comment-out res = [Element(g, sum(sub.value for sub in k)) for g, k in groupby(l, key=attrgetter('id'))] ``` which results in: ``` print(res) # [Element(1, 300), Element(2, 1), Element(3, 8)] ```
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.html#itertools.starmap) to map the items of that dictionary to the arguments to `Element` ``` from collections import defaultdict from itertools import starmap class Element: def __init__(self, id, value): self.id = id self.value = value def __repr__(self): return "Element({}, {})".format(self.id, self.value) l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)] d = defaultdict(int) for e in l: d[e.id] += e.value print(list(starmap(Element, d.items()))) # [Element(1, 300), Element(2, 1), Element(3, 8)] ```
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 `Elements` if their `id` is equal to obtain this list: ```py l = [Element(1, 300), Element(2, 1), Element(3, 8)] ``` What is the most pythonic way to do this?
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 def __repr__(self): # kudos @mesejo return "Element({}, {})".format(self.id, self.value) l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)] l.sort(key=attrgetter('id')) # if it is already sorted by 'id', comment-out res = [Element(g, sum(sub.value for sub in k)) for g, k in groupby(l, key=attrgetter('id'))] ``` which results in: ``` print(res) # [Element(1, 300), Element(2, 1), Element(3, 8)] ```
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(elem.id for elem in l) totals = [Element(i, sum(elem.value for elem in l if elem.id == i)) for i in ids] # [Element(1, 300), Element(2, 1), Element(3, 8)] ```
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 `Elements` if their `id` is equal to obtain this list: ```py l = [Element(1, 300), Element(2, 1), Element(3, 8)] ``` What is the most pythonic way to do this?
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.html#itertools.starmap) to map the items of that dictionary to the arguments to `Element` ``` from collections import defaultdict from itertools import starmap class Element: def __init__(self, id, value): self.id = id self.value = value def __repr__(self): return "Element({}, {})".format(self.id, self.value) l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)] d = defaultdict(int) for e in l: d[e.id] += e.value print(list(starmap(Element, d.items()))) # [Element(1, 300), Element(2, 1), Element(3, 8)] ```
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(elem.id for elem in l) totals = [Element(i, sum(elem.value for elem in l if elem.id == i)) for i in ids] # [Element(1, 300), Element(2, 1), Element(3, 8)] ```
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 this "file.txt" into the 3 list. Can anyone please point me to the resource? How do i proceed with retrieving these values?
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://docs.python.org/2/library/json.html)
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: ``` foos = [ {"foo":"A", "bars":[ {"bar":"R", "bazs":[ {"baz":"X"},{"baz":"Y"} ] }, {"bar":"S", "bazs":[ {"baz":"Y"} ] }, ] }, {"foo":"B", "bars":[ {"bar":"S", "bazs":[ {"baz":"X"} ] }, ] }, {"foo":"C", "bars":[ {"bar":"R", "bazs":[ {"baz":"Y"} ] }, ] }, ] ``` The combination "foo","bar","baz" is unique, and as you can see the list is not necessarily ordered by this key.
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(x, l): ks = ['foo', 'bar', 'baz'] kn = ks[l] kk = lambda i:i[kn] for k,g in groupby(sorted(x, key=kk), key=kk): kg = [dict((k,v) for k,v in i.items() if k!=kn) for i in g] d = {} d[kn] = k if l<len(ks)-1: d[ks[l+1]+'s'] = list(fun(kg, l+1)) yield d pprint(list(fun(x, 0))) ``` --- ``` [{'bars': [{'bar': 'R', 'bazs': [{'baz': 'X'}, {'baz': 'Y'}]}, {'bar': 'S', 'bazs': [{'baz': 'Y'}]}], 'foo': 'A'}, {'bars': [{'bar': 'S', 'bazs': [{'baz': 'X'}]}], 'foo': 'B'}, {'bars': [{'bar': 'R', 'bazs': [{'baz': 'Y'}]}], 'foo': 'C'}] ``` --- **note:** dict is unordered! but it's the same as yours.
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=lambda item: item[key]), lambda item: item[key])] ``` and then do ``` [{'foo': g['foo'], 'bars': group(g['bars'], "bar", "bazs")} for g in group(x, "foo", "bars")] ``` which gives the desired result for `foos`.
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: ``` foos = [ {"foo":"A", "bars":[ {"bar":"R", "bazs":[ {"baz":"X"},{"baz":"Y"} ] }, {"bar":"S", "bazs":[ {"baz":"Y"} ] }, ] }, {"foo":"B", "bars":[ {"bar":"S", "bazs":[ {"baz":"X"} ] }, ] }, {"foo":"C", "bars":[ {"bar":"R", "bazs":[ {"baz":"Y"} ] }, ] }, ] ``` The combination "foo","bar","baz" is unique, and as you can see the list is not necessarily ordered by this key.
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(x, l): ks = ['foo', 'bar', 'baz'] kn = ks[l] kk = lambda i:i[kn] for k,g in groupby(sorted(x, key=kk), key=kk): kg = [dict((k,v) for k,v in i.items() if k!=kn) for i in g] d = {} d[kn] = k if l<len(ks)-1: d[ks[l+1]+'s'] = list(fun(kg, l+1)) yield d pprint(list(fun(x, 0))) ``` --- ``` [{'bars': [{'bar': 'R', 'bazs': [{'baz': 'X'}, {'baz': 'Y'}]}, {'bar': 'S', 'bazs': [{'baz': 'Y'}]}], 'foo': 'A'}, {'bars': [{'bar': 'S', 'bazs': [{'baz': 'X'}]}], 'foo': 'B'}, {'bars': [{'bar': 'R', 'bazs': [{'baz': 'Y'}]}], 'foo': 'C'}] ``` --- **note:** dict is unordered! but it's the same as yours.
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 for k in keylist: walk = walk.setdefault(d[k], {}) node = walk.setdefault('node', {}) if not node: node[k] = d[k] parent.setdefault(k+'s',[]).append(node) walk = walk.setdefault('children', {}) parent = node return root[keylist[0]+'s'] foos = make_tree(x, ["foo","bar","baz"]) ```
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('?')+1:] ```
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 str(next(random_numbers)) for c in q) ```
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.Variable(tf.random_normal([5, 5, 32, 64], stddev=0.1)), 'wd1': tf.Variable(tf.random_normal([9*9*128, 1024], stddev=0.1)), 'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1)) } biases = { 'bc1': tf.Variable(tf.random_normal([32], stddev=0.1)), 'bc2': tf.Variable(tf.random_normal([64], stddev=0.1)), 'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)), 'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1)) } ``` Here is my conv net function: ``` def conv_basic(_input, _w, _b, _keepratio): # Input _input_r = tf.reshape(_input, shape=[-1, 72, 72, 1]) # Conv1 _conv1 = tf.nn.relu(tf.nn.bias_add( tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME') , _b['bc1'])) _pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') mean, var = tf.nn.moments(_pool1, [0, 1, 2]) _pool1 = tf.nn.batch_norm_with_global_normalization(_pool1, mean, var, 1., 0., 1e-7, 0) _pool_dr1 = tf.nn.dropout(_pool1, _keepratio) # Conv2 _conv2 = tf.nn.relu(tf.nn.bias_add( tf.nn.conv2d(_pool_dr1, _w['wc2'], strides=[1, 1, 1, 1], padding='SAME') , _b['bc2'])) _pool2 = tf.nn.max_pool(_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') mean, var = tf.nn.moments(_pool2, [0, 1, 2]) _pool2 = tf.nn.batch_norm_with_global_normalization(_pool2, mean, var, 1., 0., 1e-7, 0) _pool_dr2 = tf.nn.dropout(_pool2, _keepratio) # Vectorize _dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]]) # Fc1 _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1'])) _fc_dr1 = tf.nn.dropout(_fc1, _keepratio) # Fc2 _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2']) # Return everything out = { 'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool_dr1, 'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'dense1': _dense1, 'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out } return out ``` When I try to run this, I get an error: `"tensorflow.python.framework.errors.InvalidArgumentError: logits and labels must be same size: logits_size=[6,16] labels_size=[1,16]"` on the line `cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(_pred, y))` I've tried changing the wd1 weight values around, and apart from saying that requested shape requires a multiple of xxx, it just changes the values in the brackets. These values (especially 6) seem very arbitrary, idk where they are coming from. It would be nice for someone to explain to me how FC layer neuron amounts are chosen, as it also seems a bit arbitrary. Thanks EDIT: My full code <https://gist.github.com/EricZeiberg/f0b138d859b9ed00ce045dc6b341e0a7>
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 use 2 max pooling, which reduce the input feature map from `[1, 72, 72, 1]` to `[1, 18, 18, 64]`. At this step, you should write: ``` # Vectorize _dense1 = tf.reshape(_pool_dr2, [1, 18*18*64]) ``` You also should replace your matrix `wd1` with: ``` 'wd1': tf.Variable(tf.random_normal([18*18*64, 1024], stddev=0.1)) ``` --- In general in these situations, you need to print each shape, step after step, and realize **by yourself** where the shape doesn't correspond to what you expect.
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_node.parent if not parent: break ptag = parent.tag path = ptag + '/' + path current_node = parent return path etree._Element.get_path = get_path etree._Element.parent = None class XmlDoc(object): def __init__(self): self.root = etree.Element('root') self.doc = etree.ElementTree(self.root) def SubElement(self, parent, tag): new_node = etree.SubElement(parent, tag) new_node.parent = parent return new_node doc = XmlDoc() a1 = doc.SubElement(doc.root, 'a') a2 = doc.SubElement(doc.root, 'a') b = doc.SubElement(a2, 'b') print etree.tostring(doc.root), '\n' print 'element:'.ljust(15), a1 print 'path:'.ljust(15), a1.get_path() print 'parent:'.ljust(15), a1.parent, '\n' print 'element:'.ljust(15), a2 print 'path:'.ljust(15), a2.get_path() print 'parent:'.ljust(15), a2.parent, '\n' print 'element:'.ljust(15), b print 'path:'.ljust(15), b.get_path() print 'parent:'.ljust(15), b.parent ``` Which results in this output: ``` <root><a /><a><b /></a></root> element: <Element a at 87e3d6c> path: root/a[1] parent: <Element root at 87e3cec> element: <Element a at 87e3fac> path: root/a[2] parent: <Element root at 87e3cec> element: <Element b at 87e758c> path: root/a/b parent: <Element a at 87e3fac> ``` Now this is drastically changed from the original code, but I'm not allowed to share that. The functions aren't too inefficient but there is a dramatic performance decrease when switching from cElementTree to ElementTree which I expected, but from my experiments it seems like monkey patching cElementTree is impossible so I had to switch. What I need to know is whether there is either a way to add a method to cElementTree or if there is a more efficient way of doing this so I can gain some of my performance back. Just to let you know I am thinking of as a last resort implementing selected static typing and to compile with cython, but for certain reasons I really don't want to do that. Thanks for taking a look. EDIT: Sorry for the wrong use of the term late binding. Sometimes my vocabulary leaves something to be desired. What I meant was "monkey patching." EDIT: @Corley Brigman, Guy: Thank you very much for your answers which do address the question, however (and I should have stated this in the original post) I had completed this project before using lxml which is a wonderful library that made coding a breeze but due to new requirements (This needs to be implemented as an addon to a product called Splunk) which ties me to the python 2.7 interpreter shipped with Splunk and eliminates the possibility of adding third party libraries with the exception of django.
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 will get different results in cElementTree vs. lxml: ``` p = Element('x') q = Element('y') r = SubElement(p, 'z') q.append(r) ``` cElementTree: ``` dump(p) <x><z /></x> dump(q) <y><z /></y> ``` lxml: ``` dump(p) <x/> dump(q) <y> <z/> </y> ``` Since parents are tracked, a node can only have one parent, obviously. As you can see, the element `r` is *copied* to both trees in cElementTree, and *reparented/moved* in lxml. There are probably only a small number of use cases where this matters, but something to keep in mind.
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 to use Apache beam. For our use case Spark would be the appropriate runner to be used, and as airflow and TensorFlow are coded in python we would need to use the Apache Beam's Portable Runner (<https://beam.apache.org/documentation/runners/spark/#portability>). The problem =========== The portable runner creates the spark context inside its container and does not leave space for the driver DNS configuration making the executors inside the worker pods non-communicable to the driver (the job server). Setup ===== 1. Following the beam documentation, the job serer was implemented in the same pod as the airflow to use the local network between these two containers. Job server config: ```yaml - name: beam-spark-job-server image: apache/beam_spark_job_server:2.27.0 args: ["--spark-master-url=spark://spark-master:7077"] ``` Job server/airflow service: ```yaml apiVersion: v1 kind: Service metadata: name: airflow-scheduler labels: app: airflow-k8s spec: type: ClusterIP selector: app: airflow-scheduler ports: - port: 8793 protocol: TCP targetPort: 8793 name: scheduler - port: 8099 protocol: TCP targetPort: 8099 name: job-server - port: 7077 protocol: TCP targetPort: 7077 name: spark-master - port: 8098 protocol: TCP targetPort: 8098 name: artifact - port: 8097 protocol: TCP targetPort: 8097 name: java-expansion ``` The ports 8097,8098 and 8099 are related to the job server, 8793 to airflow, and 7077 to the spark master. Development/Errors ================== 1. When testing a simple beam example `python -m apache_beam.examples.wordcount --output ./data_test/ --runner=PortableRunner --job_endpoint=localhost:8099 --environment_type=LOOPBACK` from the airflow container I get the following response on the airflow pod: ``` Defaulting container name to airflow-scheduler. Use 'kubectl describe pod/airflow-scheduler-local-f685b5bc7-9d7r6 -n airflow-main-local' to see all of the containers in this pod. airflow@airflow-scheduler-local-f685b5bc7-9d7r6:/opt/airflow$ python -m apache_beam.examples.wordcount --output ./data_test/ --runner=PortableRunner --job_endpoint=localhost:8099 --environment_type=LOOPBACK INFO:apache_beam.internal.gcp.auth:Setting socket default timeout to 60 seconds. INFO:apache_beam.internal.gcp.auth:socket default timeout is 60.0 seconds. INFO:oauth2client.client:Timeout attempting to reach GCE metadata service. WARNING:apache_beam.internal.gcp.auth:Unable to find default credentials to use: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information. Connecting anonymously. INFO:apache_beam.runners.worker.worker_pool_main:Listening for workers at localhost:35837 WARNING:root:Make sure that locally built Python SDK docker image has Python 3.7 interpreter. INFO:root:Default Python SDK image for environment is apache/beam_python3.7_sdk:2.27.0 INFO:apache_beam.runners.portability.portable_runner:Environment "LOOPBACK" has started a component necessary for the execution. Be sure to run the pipeline using with Pipeline() as p: p.apply(..) This ensures that the pipeline finishes before this program exits. INFO:apache_beam.runners.portability.portable_runner:Job state changed to STOPPED INFO:apache_beam.runners.portability.portable_runner:Job state changed to STARTING INFO:apache_beam.runners.portability.portable_runner:Job state changed to RUNNING ``` And the worker log: ``` 21/02/19 19:50:00 INFO Worker: Asked to launch executor app-20210219194804-0000/47 for BeamApp-root-0219194747-7d7938cf_51452c51-dffe-4c61-bcb7-60c7779e3256 21/02/19 19:50:00 INFO SecurityManager: Changing view acls to: root 21/02/19 19:50:00 INFO SecurityManager: Changing modify acls to: root 21/02/19 19:50:00 INFO SecurityManager: Changing view acls groups to: 21/02/19 19:50:00 INFO SecurityManager: Changing modify acls groups to: 21/02/19 19:50:00 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(root); groups with view permissions: Set(); users with modify permissions: Set(root); groups with modify permissions: Set() 21/02/19 19:50:00 INFO ExecutorRunner: Launch command: "/usr/local/openjdk-8/bin/java" "-cp" "/opt/spark/conf/:/opt/spark/jars/*" "-Xmx1024M" "-Dspark.driver.port=44447" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "spark://CoarseGrainedScheduler@airflow-scheduler-local-f685b5bc7-9d7r6:44447" "--executor-id" "47" "--hostname" "172.18.0.3" "--cores" "1" "--app-id" "app-20210219194804-0000" "--worker-url" "spark://Worker@172.18.0.3:35837" 21/02/19 19:50:02 INFO Worker: Executor app-20210219194804-0000/47 finished with state EXITED message Command exited with code 1 exitStatus 1 21/02/19 19:50:02 INFO ExternalShuffleBlockResolver: Clean up non-shuffle files associated with the finished executor 47 21/02/19 19:50:02 INFO ExternalShuffleBlockResolver: Executor is not registered (appId=app-20210219194804-0000, execId=47) 21/02/19 19:50:02 INFO Worker: Asked to launch executor app-20210219194804-0000/48 for BeamApp-root-0219194747-7d7938cf_51452c51-dffe-4c61-bcb7-60c7779e3256 21/02/19 19:50:02 INFO SecurityManager: Changing view acls to: root 21/02/19 19:50:02 INFO SecurityManager: Changing modify acls to: root 21/02/19 19:50:02 INFO SecurityManager: Changing view acls groups to: 21/02/19 19:50:02 INFO SecurityManager: Changing modify acls groups to: 21/02/19 19:50:02 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(root); groups with view permissions: Set(); users with modify permissions: Set(root); groups with modify permissions: Set() 21/02/19 19:50:02 INFO ExecutorRunner: Launch command: "/usr/local/openjdk-8/bin/java" "-cp" "/opt/spark/conf/:/opt/spark/jars/*" "-Xmx1024M" "-Dspark.driver.port=44447" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "spark://CoarseGrainedScheduler@airflow-scheduler-local-f685b5bc7-9d7r6:44447" "--executor-id" "48" "--hostname" "172.18.0.3" "--cores" "1" "--app-id" "app-20210219194804-0000" "--worker-url" "spark://Worker@172.18.0.3:35837" 21/02/19 19:50:04 INFO Worker: Executor app-20210219194804-0000/48 finished with state EXITED message Command exited with code 1 exitStatus 1 21/02/19 19:50:04 INFO ExternalShuffleBlockResolver: Clean up non-shuffle files associated with the finished executor 48 21/02/19 19:50:04 INFO ExternalShuffleBlockResolver: Executor is not registered (appId=app-20210219194804-0000, execId=48) 21/02/19 19:50:04 INFO Worker: Asked to launch executor app-20210219194804-0000/49 for BeamApp-root-0219194747-7d7938cf_51452c51-dffe-4c61-bcb7-60c7779e3256 21/02/19 19:50:04 INFO SecurityManager: Changing view acls to: root 21/02/19 19:50:04 INFO SecurityManager: Changing modify acls to: root 21/02/19 19:50:04 INFO SecurityManager: Changing view acls groups to: 21/02/19 19:50:04 INFO SecurityManager: Changing modify acls groups to: 21/02/19 19:50:04 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(root); groups with view permissions: Set(); users with modify permissions: Set(root); groups with modify permissions: Set() 21/02/19 19:50:04 INFO ExecutorRunner: Launch command: "/usr/local/openjdk-8/bin/java" "-cp" "/opt/spark/conf/:/opt/spark/jars/*" "-Xmx1024M" "-Dspark.driver.port=44447" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "spark://CoarseGrainedScheduler@airflow-scheduler-local-f685b5bc7-9d7r6:44447" "--executor-id" "49" "--hostname" "172.18.0.3" "--cores" "1" "--app-id" "app-20210219194804-0000" "--worker-url" "spark://Worker@172.18.0.3:35837" . . . ``` As we can see, the executor is being exited constantly, and by what I know this issue is created by the missing communication between the executor and the driver (the job server in this case). Also, the "--driver-url" is translated to the driver pod name using the random port "-Dspark.driver.port". As we can't define the name of the service, the worker tries to use the original name from the driver and to use a randomly generated port. As the configuration comes from the driver, changing the default conf files in the worker/master doesn't create any results. Using [this answer](https://stackoverflow.com/questions/64488060/apache-beam-cannot-increase-executor-memory-it-is-fixed-at-1024m-despite-usi) as an example, I tried to use the env variable `SPARK_PUBLIC_DNS` in the job server but this didn't result in any changes in the worker logs. Obs --- Using directly in kubernetes a spark job `kubectl run spark-base --rm -it --labels="app=spark-client" --image bde2020/spark-base:2.4.5-hadoop2.7 -- bash ./spark/bin/pyspark --master spark://spark-master:7077 --conf spark.driver.host=spark-client` having the service: ```yaml apiVersion: v1 kind: Service metadata: name: spark-client spec: selector: app: spark-client clusterIP: None ``` I get a full working pyspark shell. If I omit the --conf parameter I get the same behavior as the first setup (exiting executors indefinitely) ``` 21/02/19 20:21:02 INFO Worker: Executor app-20210219202050-0002/4 finished with state EXITED message Command exited with code 1 exitStatus 1 21/02/19 20:21:02 INFO ExternalShuffleBlockResolver: Clean up non-shuffle files associated with the finished executor 4 21/02/19 20:21:02 INFO ExternalShuffleBlockResolver: Executor is not registered (appId=app-20210219202050-0002, execId=4) 21/02/19 20:21:02 INFO Worker: Asked to launch executor app-20210219202050-0002/5 for Spark shell 21/02/19 20:21:02 INFO SecurityManager: Changing view acls to: root 21/02/19 20:21:02 INFO SecurityManager: Changing modify acls to: root 21/02/19 20:21:02 INFO SecurityManager: Changing view acls groups to: 21/02/19 20:21:02 INFO SecurityManager: Changing modify acls groups to: 21/02/19 20:21:02 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(root); groups with view permissions: Set(); users with modify permissions: Set(root); groups with modify permissions: Set() 21/02/19 20:21:02 INFO ExecutorRunner: Launch command: "/usr/local/openjdk-8/bin/java" "-cp" "/opt/spark/conf/:/opt/spark/jars/*" "-Xmx1024M" "-Dspark.driver.port=46161" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "spark://CoarseGrainedScheduler@spark-base:46161" "--executor-id" "5" "--hostname" "172.18.0.20" "--cores" "1" "--app-id" "app-20210219202050-0002" "--worker-url" "spark://Worker@172.18.0.20:45151" ```
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 would not need to start the `beam_spark_job_server` container at all. ```sh python -m apache_beam.examples.wordcount \ --output ./data_test/ \ --runner=SparkRunner \ --spark_submit_uber_jar \ --spark_master_url=spark://spark-master:7077 \ --environment_type=LOOPBACK ``` 2. You can pass the properties through a Spark configuration file. Create the Spark configuration file, and add `spark.driver.host` and whatever other properties you need. In the `docker run` command for the job server, mount that configuration file to the container, and set the `SPARK_CONF_DIR` environment variable to point to that directory. 3. If that neither of those work for you, you can alternatively build your own customized version of the job server container. Pull Beam source from Github. Check out the release branch you want to use (e.g. `git checkout origin/release-2.28.0`). Modify the entrypoint [spark-job-server.sh](https://github.com/apache/beam/blob/92ddb5c0bf61174e2153eef2a294a61bc924156f/runners/spark/job-server/container/spark-job-server.sh#L28) and set `-Dspark.driver.host=x` there. Then build the container using `./gradlew :runners:spark:job-server:container:docker -Pdocker-repository-root="your-repo" -Pdocker-tag="your-tag"`.
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-spark> . If it is useful for you, can help me to 'Star' the repository
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 Hebrew text I am trying to show. This is what I get: [![What I get](https://i.stack.imgur.com/tDSzF.png)](https://i.stack.imgur.com/tDSzF.png) As you can see, It shows this weird text instead of the text I need to show... My code, My main script: ``` import kivy from kivy.app import App from kivy.uix.button import Button from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.label import Label from kivy.uix.widget import Widget from kivy.properties import ObjectProperty import getData class MainScreen(Widget): ttc = ObjectProperty(None) ct = ObjectProperty(None) def btn(self): self.ct.text = getData.HE_EN(text=self.ttc.text.lower()) pass class MyApp(App): def build(self): return MainScreen() if __name__ == "__main__": MyApp().run() ``` My "my.kv" file: ``` <MainScreen>: ttc: ttc ct: ct GridLayout: size: root.width, root.height cols: 1 TextInput: text: "" id: ttc Button: text: "CONVERT" on_press: root.btn() TextInput: text: "CONVERTED TEXT" id: ct ``` There is no need to show the getData.py script that returns the text in Hebrew because it doesn't really matter... The expected result is to get the text I want in the TextInput even thought I don't really manage to. Please help me fixing my issue, I really do need that...
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 LabelBase` and then registered the font: `LabelBase.register(name="Arial", fn_regular="Arial.ttf")`, To tell the TextInput that I want to set the font to that I just added to my .kv file under the widget 'font\_name: "Arial"' and that solved the problem.
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, keycode, text, modifiers): if keycode[1] == "backspace": self.text = self.text[1:] def insert_text(self, theText, from_undo=False): self.text = theText + self.text ```
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, timestamp)) ``` When I run a SELECT statement to retrieve the timestamps, it returns tuples instead: ``` cursor.execute("SELECT pubDate FROM articles") rows = cursor.fetchall() for row in rows: print(row) ``` This is the returned row: ``` (datetime.datetime(2015, 12, 9, 6, 47, 4, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=660, name=None)),) ``` How can I retrieve the datetime object directly? I've looked up a few other related questions (see [here](https://stackoverflow.com/questions/32184465/how-to-cast-date-to-string-in-psycopg2) and [here](https://stackoverflow.com/questions/28724968/python-tuple-returns-datetime-datetime)) but can't seem to find the answer. Probably overlooking something simple here but any help would be much appreciated!
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 `SELECT` you can use the cursor as an iterator, unpacking the row tuples as needed: ``` cursor.execute("SELECT pubDate FROM articles") for pub_date, in cursor: # note the comma after `pub_date` print(pub_date) ```
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, timestamp)) ``` When I run a SELECT statement to retrieve the timestamps, it returns tuples instead: ``` cursor.execute("SELECT pubDate FROM articles") rows = cursor.fetchall() for row in rows: print(row) ``` This is the returned row: ``` (datetime.datetime(2015, 12, 9, 6, 47, 4, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=660, name=None)),) ``` How can I retrieve the datetime object directly? I've looked up a few other related questions (see [here](https://stackoverflow.com/questions/32184465/how-to-cast-date-to-string-in-psycopg2) and [here](https://stackoverflow.com/questions/28724968/python-tuple-returns-datetime-datetime)) but can't seem to find the answer. Probably overlooking something simple here but any help would be much appreciated!
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 articles" cursor.execute(query) rs = cursor.fetchall()[0] print rs[0], rs[1] print type(rs[1]) ``` Output: ``` insert into articles values ('The Title', '2015-05-20T13:56:02-07:00'::timestamptz) The Title 2015-05-20 17:56:02-03:00 <type 'datetime.datetime'> ```
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, timestamp)) ``` When I run a SELECT statement to retrieve the timestamps, it returns tuples instead: ``` cursor.execute("SELECT pubDate FROM articles") rows = cursor.fetchall() for row in rows: print(row) ``` This is the returned row: ``` (datetime.datetime(2015, 12, 9, 6, 47, 4, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=660, name=None)),) ``` How can I retrieve the datetime object directly? I've looked up a few other related questions (see [here](https://stackoverflow.com/questions/32184465/how-to-cast-date-to-string-in-psycopg2) and [here](https://stackoverflow.com/questions/28724968/python-tuple-returns-datetime-datetime)) but can't seem to find the answer. Probably overlooking something simple here but any help would be much appreciated!
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 `SELECT` you can use the cursor as an iterator, unpacking the row tuples as needed: ``` cursor.execute("SELECT pubDate FROM articles") for pub_date, in cursor: # note the comma after `pub_date` print(pub_date) ```
``` 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 articles" cursor.execute(query) rs = cursor.fetchall()[0] print rs[0], rs[1] print type(rs[1]) ``` Output: ``` insert into articles values ('The Title', '2015-05-20T13:56:02-07:00'::timestamptz) The Title 2015-05-20 17:56:02-03:00 <type 'datetime.datetime'> ```
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 CRLfile: none ``` I know about "export GIT\_SSL\_NO\_VERIFY=1", but how to implement it in a python library ?
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 suggested by [@Christopher](https://stackoverflow.com/a/11622001/248390): ```py git.Repo.clone_from( 'https://example.net/path/to/repo.git', 'local_destination', branch='master', depth=1, config='http.sslVerify=false', ) ```
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 would have to manipulate python's environment like so: ``` import git import os os.environ['GIT_SSL_NO_VERIFY'] = "1" repo = git.Repo.clone_from('https://xxx', '/home/xxx/lala') ```
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]) ``` and it outputs ``` array([3, 7, 1, 1, 2, 3, 2]) ``` as you can see it is missing the first count 1. I've tried `np.split` and then get the sizes of each segments but it does not seem to be optimistic. Is there more elegant "pythonic" solution?
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 `boolean` concatenation - ``` np.diff(np.flatnonzero(np.concatenate(([True], a[1:]!= a[:-1], [True] )))) ``` **Runtime test** For the setup, let's create a bigger dataset with islands of `0s` and `1s` and for a fair benchmarking as with the given sample, let's have the island lengths vary between `1` and `7` - ``` In [257]: n = 100000 # thus would create 100000 pair of islands In [258]: a = np.repeat(np.arange(n)%2, np.random.randint(1,7,(n))) # Approach #1 proposed in this post In [259]: %timeit np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size]) 100 loops, best of 3: 2.13 ms per loop # Approach #2 proposed in this post In [260]: %timeit np.diff(np.flatnonzero(np.concatenate(([True], a[1:]!= a[:-1], [True] )))) 1000 loops, best of 3: 1.21 ms per loop # @Vineet Jain's soln In [261]: %timeit [ sum(1 for i in g) for k,g in groupby(a)] 10 loops, best of 3: 61.3 ms per loop ```
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]) ``` and it outputs ``` array([3, 7, 1, 1, 2, 3, 2]) ``` as you can see it is missing the first count 1. I've tried `np.split` and then get the sizes of each segments but it does not seem to be optimistic. Is there more elegant "pythonic" solution?
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 `boolean` concatenation - ``` np.diff(np.flatnonzero(np.concatenate(([True], a[1:]!= a[:-1], [True] )))) ``` **Runtime test** For the setup, let's create a bigger dataset with islands of `0s` and `1s` and for a fair benchmarking as with the given sample, let's have the island lengths vary between `1` and `7` - ``` In [257]: n = 100000 # thus would create 100000 pair of islands In [258]: a = np.repeat(np.arange(n)%2, np.random.randint(1,7,(n))) # Approach #1 proposed in this post In [259]: %timeit np.diff(np.r_[0,np.flatnonzero(np.diff(a))+1,a.size]) 100 loops, best of 3: 2.13 ms per loop # Approach #2 proposed in this post In [260]: %timeit np.diff(np.flatnonzero(np.concatenate(([True], a[1:]!= a[:-1], [True] )))) 1000 loops, best of 3: 1.21 ms per loop # @Vineet Jain's soln In [261]: %timeit [ sum(1 for i in g) for k,g in groupby(a)] 10 loops, best of 3: 61.3 ms per loop ```
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.where(diff_a != 0)[0] print(f'Array of positions where non zero elements are present in diff_a array: {non_zero_pos_arr}') diff_non_zero_pos_arr = np.diff(non_zero_pos_arr) print(f'Result Array except for first and last element: {diff_non_zero_pos_arr}') ans_first_ele = non_zero_pos_arr[0] + 1 ans_last_ele = len(diff_a) - non_zero_pos_arr[-1] ans = np.array([], dtype=np.int8) ans = np.append(ans, ans_first_ele) ans = np.append(ans, diff_non_zero_pos_arr) ans = np.append(ans, ans_last_ele) print(f'Result Array: {ans}') ``` Output: ```none a: [0 1 1 1 0 0 0 0 0 0 0 1 0 1 1 0 0 0 1 1 0 0] diff_a: [ 1 0 0 -1 0 0 0 0 0 0 1 -1 1 0 -1 0 0 1 0 -1 0] Array of positions where non zero elements are present in diff_a array: [ 0 3 10 11 12 14 17 19] Result Array except for first and last element: [3 7 1 1 2 3 2] Result Array: [1 3 7 1 1 2 3 2 2] ```
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]) ``` and it outputs ``` array([3, 7, 1, 1, 2, 3, 2]) ``` as you can see it is missing the first count 1. I've tried `np.split` and then get the sizes of each segments but it does not seem to be optimistic. Is there more elegant "pythonic" solution?
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.where(diff_a != 0)[0] print(f'Array of positions where non zero elements are present in diff_a array: {non_zero_pos_arr}') diff_non_zero_pos_arr = np.diff(non_zero_pos_arr) print(f'Result Array except for first and last element: {diff_non_zero_pos_arr}') ans_first_ele = non_zero_pos_arr[0] + 1 ans_last_ele = len(diff_a) - non_zero_pos_arr[-1] ans = np.array([], dtype=np.int8) ans = np.append(ans, ans_first_ele) ans = np.append(ans, diff_non_zero_pos_arr) ans = np.append(ans, ans_last_ele) print(f'Result Array: {ans}') ``` Output: ```none a: [0 1 1 1 0 0 0 0 0 0 0 1 0 1 1 0 0 0 1 1 0 0] diff_a: [ 1 0 0 -1 0 0 0 0 0 0 1 -1 1 0 -1 0 0 1 0 -1 0] Array of positions where non zero elements are present in diff_a array: [ 0 3 10 11 12 14 17 19] Result Array except for first and last element: [3 7 1 1 2 3 2] Result Array: [1 3 7 1 1 2 3 2 2] ```