Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
1,904,600
54,920,008
Jupyter Notebook: Print 2d array, where each and every row and column is in a single line
<p>When I try to print a 28 x 28 2d array using the code </p> <pre><code>print(x_test[0]) </code></pre> <p>I get output like this:</p> <pre><code> [[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 84 185 159 151 60 36 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 222 254 254 254 254 241 198 198 198 198 198 198 198 198 170 52 0 0 0 0 0 0] [ 0 0 0 0 0 0 67 114 72 114 163 227 254 225 254 254 254 250 229 254 254 140 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 17 66 14 67 67 67 59 21 236 254 106 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 83 253 209 18 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 22 233 255 83 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 129 254 238 44 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 59 249 254 62 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 133 254 187 5 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 205 248 58 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 126 254 182 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 75 251 240 57 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 19 221 254 166 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 3 203 254 219 35 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 38 254 254 77 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 31 224 254 115 1 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 133 254 254 52 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 61 242 254 254 52 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 121 254 254 219 40 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 121 254 207 18 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]] </code></pre> <p>I have even tried other methods using pandas Dataframe. But it doesn't display some of the output values. All I just want is a 28 rows and 28 columns for my 28 x 28 2d array. I'm using python on Jupyter notebook.</p>
<p>You could make a little printing function to do this. You will need to do a little bit of formatting, and also watch the window width.</p> <pre><code>In [4]: my_matrix = [[1,23,0], [55,4,-1], [0,0,2]] In [5]: for row in my_matrix: ...: for item in row: ...: print('%3d ' % item, end="") ...: print() ...: 1 23 0 55 4 -1 0 0 2 </code></pre> <p>if you have 28 columns and you use 3 spaces per number for alignment and a space between, it's getting kinda wide, so watch the wrap-around.</p>
python|jupyter-notebook|ipython
0
1,904,601
54,983,239
pass url parameter to serializer
<p>Suppose my url be, <strong>POST</strong> : <code>/api/v1/my-app/my-model/?myVariable=foo</code></p> <p>How can I pass the <code>myVariable</code> to the serializer?</p> <pre><code># serializer.py class MySerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = MyModel def custom_validator(self): # how can i get the "myVariable" value here? pass def validate(self, attrs): attrs = super().validate(attrs) self.custom_validator() return attrs # views.py class MyViewset(ModelViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer </code></pre>
<p>You can access the variable via <a href="https://www.django-rest-framework.org/api-guide/requests/#query_params" rel="noreferrer"><strong><code>request.query_params</code></strong></a> attribute<br></p> <h2>How it's possible through serializer ?</h2> <p>The <strong><code>ModelViewSet</code></strong> class passing the <code>request</code> object and <code>view</code> object to the serializer as <em>serializer context data</em>, and it's accessible in serializer in <strong><code>context</code></strong> variable <br><br></p> <h3>Method-1: Use directly the <code>request</code> object in serializer</h3> <pre><code># serializer.py class MySerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = MyModel <b>def custom_validator(self): request_object = self.context['request'] myVariable = request_object.query_params.get('myVariable') if myVariable is not None: # use "myVariable" here pass</b> def validate(self, attrs): attrs = super().validate(attrs) self.custom_validator() return attrs</code></pre> <p><br></p> <h3>Method-2: Override the <code>get_serializer_context()</code> method</h3> <pre><code># serializer.py class MySerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = MyModel <b>def custom_validator(self): myVariable = self.context['myVariable'] #use "myVariable" here</b> def validate(self, attrs): attrs = super().validate(attrs) self.custom_validator() return attrs # views.py class MyViewset(ModelViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer <b>def get_serializer_context(self): context = super().get_serializer_context() context.update( { "myVariable": self.request.query_params.get('myVariable') } ) return context</b></code></pre>
python|django|django-rest-framework
14
1,904,602
73,785,803
Filter grouped data based on stage ordering
<p>My data consist of rows recording what stage an ID is in on a certain date. Ideally, each ID should proceed to stage 4 directionally, though it need not go through every stage. For example ID &quot;A&quot; below goes throgh stages 1-&gt;2-&gt;4. Sometimes (for a variety of possible reasons) an ID is returned to a previous stage. The data are sorted by date within each ID:</p> <pre><code>df = pd.DataFrame( {&quot;ID&quot;: [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;C&quot;,&quot;C&quot;,&quot;C&quot;,&quot;C&quot;,&quot;C&quot;,&quot;C&quot;], &quot;Stage&quot;:[4,2,1,4,3,4,3,2,1,4,3,2,1,2,1],\ &quot;Date&quot;:['2022-09-18','2022-09-17','2022-09-16','2022-09-20','2022-09-19','2022-09-18','2022-09-17','2022-09-16','2022-09-15',\ '2022-09-20','2022-09-19','2022-09-18','2022-09-17','2022-09-16','2022-09-15']} ) print(df) ID Stage Date 0 A 4 2022-09-18 1 A 2 2022-09-17 2 A 1 2022-09-16 3 B 4 2022-09-20 4 B 3 2022-09-19 5 B 4 2022-09-18 6 B 3 2022-09-17 7 B 2 2022-09-16 8 B 1 2022-09-15 9 C 4 2022-09-20 10 C 3 2022-09-19 11 C 2 2022-09-18 12 C 1 2022-09-17 13 C 2 2022-09-16 14 C 1 2022-09-15 </code></pre> <p>I would like to drop all rows of data for each ID that occur before the most recent time that it is sent back to a previous stage. I would get something like this:</p> <pre><code>print(df_filtered) ID Stage Date 0 A 4 2022-09-18 1 A 2 2022-09-17 2 A 1 2022-09-16 3 B 4 2022-09-20 4 B 3 2022-09-19 5 C 4 2022-09-20 6 C 3 2022-09-19 7 C 2 2022-09-18 8 C 1 2022-09-17 </code></pre> <p>Notice that A has not changed as it moved directionally through the process, B has dropped all data before it was sent back to Stage 3 on 2022-09-19, and C has dropped the two rows before it was returned to Stage 1 on 2022-09-17. This is a greatly simplified case , but in the true data an ID might be returned to a previous stage several times, including within the same stage. For example, an ID might be sent from stage 2 back to stage 2.</p> <p>Is there a clean way to get from df to df_filtered without using for loops?</p>
<p>IIUC, sort the dates, then per group, check if there is an increase in Stage and drop the values afterwards:</p> <pre><code>m = (df # ensure the dates are in decreasing order # optional if the dates are already in descending order .sort_values(by=['ID', 'Date'], ascending=[True, False]) # for each group, if Stage increases, flag this and the successive rows .groupby('ID')['Stage'].apply(lambda x: x.diff().gt(0).cummax()) ) # select the non-flagged rows out = df[~m] </code></pre> <p>output:</p> <pre><code> ID Stage Date 0 A 4 2022-09-18 1 A 2 2022-09-17 2 A 1 2022-09-16 3 B 4 2022-09-20 4 B 3 2022-09-19 9 C 4 2022-09-20 10 C 3 2022-09-19 11 C 2 2022-09-18 12 C 1 2022-09-17 </code></pre> <p>intermediates:</p> <pre><code> ID Stage Date diff gt(0) cummax 0 A 4 2022-09-18 NaN False False 1 A 2 2022-09-17 -2.0 False False 2 A 1 2022-09-16 -1.0 False False 3 B 4 2022-09-20 NaN False False 4 B 3 2022-09-19 -1.0 False False 5 B 4 2022-09-18 1.0 True True 6 B 3 2022-09-17 -1.0 False True 7 B 2 2022-09-16 -1.0 False True 8 B 1 2022-09-15 -1.0 False True 9 C 4 2022-09-20 NaN False False 10 C 3 2022-09-19 -1.0 False False 11 C 2 2022-09-18 -1.0 False False 12 C 1 2022-09-17 -1.0 False False 13 C 2 2022-09-16 1.0 True True 14 C 1 2022-09-15 -1.0 False True </code></pre>
python|pandas
1
1,904,603
12,940,389
bad character regexp in python
<p>I have a string</p> <pre><code>1563:37say: 0 kl4|us: !!alias kl4 </code></pre> <p>and I need to extract some information. I'm trying with this Python code:</p> <pre><code> import re x = "1563:37say: 0 kl4us: !!alias kl4" res = re.search( r"(?P&lt;say&gt;say(team)?): (?P&lt;id&gt;\d+) (?P&lt;name&gt;\w+): (?P&lt;text&gt;.*)",x) slot= res.group("id") text = res.group("text") say = res.group("say") name = res.group("name") </code></pre> <p>This code works fine. Why if I have a character <code>|</code> or <code>*</code> into my string this regexp doesn't work?</p> <p>For example:</p> <pre><code> import re x = "1563:37say: 0 kl4|us: !!alias kl4" res = re.search( r"(?P&lt;say&gt;say(team)?): (?P&lt;id&gt;\d+) (?P&lt;name&gt;\w+): (?P&lt;text&gt;.*)",x) slot= res.group("id") text = res.group("text") say = res.group("say") name = res.group("name") </code></pre> <p>Anyone can help me?</p> <p>Thanks a lot</p>
<p>Based on where you added the "|", it looks like you expect "|" and "*" to be matched by <code>\w</code>, but <code>\w</code> only matches letters, digits, and "_". To match those characters as well, change the <code>\w</code> to <code>[\w|*]</code>:</p> <pre><code>res = re.search( r"(?P&lt;say&gt;say(team)?): (?P&lt;id&gt;\d+) (?P&lt;name&gt;[\w|*]+): (?P&lt;text&gt;.*)",x) </code></pre>
python|regex
5
1,904,604
24,638,507
Slicing Lists with Variable Based Index
<p>How can I slice a list with an index that is based off of a variable?</p> <p>i.e.</p> <pre><code>splitMe = range(0,10) startPlace = 3 endPlace = 5 splitMe[startPlace:endPlace] #&lt;------This is essentially what I need </code></pre> <p>This way I can input different numbers into startPlace and endPlace and get a different slice. This probably seems trivial, but I am cutting sections out of 230,000 lines of data. There are calculations behind startPlace and endPlace that have to do with dates and times. </p> <p>This is what I have now:</p> <pre><code>#Find matching data with datetime for a, line in enumerate (Time): if line == startDate: print "Slice starts at:", a for c, line in enumerate (Time): if line == endDate: print "Slice ends at:", c #Create lists slice_laser_c = [x for x in laser_C if a &lt;= x &lt; c] </code></pre> <p><strong>EDIT</strong> When I run this code, it prints "Slice starts at: 0" and "Slice ends at: 5" which is exactly what it"s supposed to do. <strong>END EDIT</strong> When I print slice_laser_c I get</p> <pre><code>[] #&lt;----- Essentially, this is the problem </code></pre> <p>In a simple sense, this is what's going on:</p> <pre><code>big_list = range(0,10) a = 2 c = 5 BetweenList = [x for x in big_list if a &lt;= x &lt; c] print BetweenList </code></pre>
<p>The problem appers to be that you are iterating right through all the <code>Times</code> without stopping when you find the values you want. Therefore at the end of both loops <code>a</code> and <code>c</code> are at their maximum value. Maybe you want to <code>break</code> the loop once you have found the value you want?</p>
python|variables|indexing|splice
0
1,904,605
41,164,436
Import Error: no module named, after file moved to another folder
<p>I recently moved a utils.py file into a utils folder. Folder structure:</p> <pre><code>+ v0 -handlers.py -utils.py + utils -__init__.py -base.py </code></pre> <p>Now, I moved the methods in utils.py to base.py. </p> <p>I am getting import error in handlers.py at:</p> <pre><code>from utils.base import * </code></pre> <p>Note: I deleted the utils.py file.</p> <p>Upon debugging, I noticed that handlers.py is still looking up for utils.base in utils.py That file is nowhere in my project anymore. I have no clue where this handlers.py, looking up for this utils.py file instead of the utils folder.</p>
<p>If you are debugging via PyCharm or IntelliJ, you may need to delete the test run config for that test.</p>
python|importerror
0
1,904,606
39,980,281
TypeError: unsupported operand type(s) for +: 'Cursor' and 'Cursor'
<p>I want to be able to store two collections in variable to be able to view and sort through them. However, I seem to be getting the error above. My code is in python and look like this:</p> <pre><code> from pymongo import MongoClient db = MongoClient('10.39.165.193', 27017)['mean-dev'] cursor1 = db.Build_Progress.find() cursor2 = db.build_lookup.find() joincursors = cursor1+ cursor2 for document in cook: print(document) </code></pre>
<p>You need to <a href="https://docs.python.org/3.6/library/itertools.html#itertools.chain" rel="nofollow"><code>chain</code></a> the two cursors like this:</p> <pre><code>from itertools import chain for document in chain(cursor1, cursor2): print(document) </code></pre>
python|mongodb|pymongo
0
1,904,607
29,211,173
Accessing "internal variables" of list
<p>I created a subclass of list that writes to file every so often so that I can recover data even in the event of a catastrophic failure. However, I'm not sure I'm handling IO in the best way.</p> <pre><code>import cPickle class IOlist(list): def __init__(self, filename, sentinel): list.__init__(self) self.filename = filename def save(self): with open(self.filename, 'wb') as ouf: cPickle.dump(list(self), ouf) def load(self): with open(self.filename, 'rb') as inf: lst = cPickle.load(inf) for item in lst: self.append(item) </code></pre> <p>Adding every object back into the list one-by-one after I read in the file feels wrong. Is there a better way to do this? I was hoping you could access the internals of a list object and do something like</p> <pre><code> def load(self): with open(self.filename, 'rb') as inf: self.list_items = cPickle.load(inf) </code></pre> <p>Unfortunately <code>vars(list)</code> seems to show that list does not have a <code>__dict__</code> attribute and I don't know where else to look for where the items of a list are stored.</p> <p>And I tried <code>self = cPickle.load(inf)</code> but that didn't work either.</p>
<p>You should be able to load the pickle directly into the list using</p> <pre><code>def load(self): with open(self.filename, 'rb') as inf: self[:] = cPickle.load(inf) </code></pre> <p>One other observation, if something goes wrong during the save, you might obliterate the latest persisted list, leaving no method of recovery. You would be better off using a separate file (perhaps using tempfile or similar, or just manage 2 files), and then replacing the previous file once you are certain that the list has successfully been persisted. </p>
python|python-2.7|data-structures|io
4
1,904,608
29,187,495
Seaborn distplot: y axis problems with multiple kdeplots
<p>I am currently plotting 3 kernel density estimations together on the same graph. I assume that kdeplots use relative frequency as the y value, however for some of my data the kdeplot has frequencies way above 1. </p> <p>code I'm using:</p> <pre><code>sns.distplot(data1, kde_kws={"color": "b", "lw": 1.5, "shade": "False", "kernel": "gau", "label": "t"}, hist=False) </code></pre> <p>Does anyone know how I can make sure that the kdeplot either makes y value relative frequency, or allow me to adjust the ymax axis limit automatically to the maximum frequency calculated?</p>
<p>Okay so I figured out that I just needed to set the autocaling to <code>Tight</code>, that way it didn't give negative values on the scale.</p>
python|matplotlib|seaborn|kernel-density
2
1,904,609
51,659,240
How to club different excel files into one workbook with different sheet names in python
<p>I have two excel workbooks. </p> <p>One with 3 sheets and the other with only one sheet. I am trying to combine these two into one workbook. <strong>This workbook should have 4 sheets.</strong></p> <pre><code>from pandas import ExcelWriter writer = ExcelWriter("Sample.xlsx") for filename in glob.glob("*.xlsx"): df_excel = pd.read_excel(filename) (_, f_name) = os.path.split(filename) (f_short_name, _) = os.path.splitext(f_name) df_excel.to_excel(writer, f_short_name, index=False) writer.save() </code></pre> <p>Doing this gives me a workbook, but with only 2 sheets. First sheet of the first workbook and second sheet of second workbook.</p> <p>How to get all the 4 sheets in one workbook?</p>
<p>You have to loop through the sheet names. See the below code: </p> <pre><code>from pandas import ExcelWriter import glob import os import pandas as pd writer = ExcelWriter("output.xlsx") for filename in glob.glob("*.xlsx"): excel_file = pd.ExcelFile(filename) (_, f_name) = os.path.split(filename) (f_short_name, _) = os.path.splitext(f_name) for sheet_name in excel_file.sheet_names: df_excel = pd.read_excel(filename, sheet_name=sheet_name) df_excel.to_excel(writer, f_short_name+'_'+sheet_name, index=False) writer.save() </code></pre>
python|excel|python-3.x|pandas
12
1,904,610
51,562,106
Python break the command line, why?
<p>I just want to launch my program written in C++ from a Python script. I wrote the following script:</p> <pre><code>import subprocess subprocess.call(['l:\Proj\Silium.exe', '--AddWatch c:\fff.txt']) </code></pre> <p>But to my c++ application the parameter <code>"--AddWatch c:\fff.txt"</code> arrives without hyphens - it arrives as <code>"AddWatch c:\fff.txt"</code>. So my program doesn't work. </p> <p>Why does this happen, and how can I fix it?</p> <p>UPD: thx for comments - yours answer helps!</p>
<p>I explain the issue and the solution. I need to launch my application in the following way:</p> <pre><code>l:\Proj\Silium.exe --AddWatch c:\fff.txt </code></pre> <p>When I tried to do this using some hint from internet:</p> <pre><code>import subprocess subprocess.call(['l:\Proj\Silium.exe', '--AddWatch c:\fff.txt']) </code></pre> <p>the key "--AddWatch" arrives to my program without hyphens - like "AddWatch".</p> <p>The solution is quite simple:</p> <pre><code>import subprocess subprocess.call(['l:\Proj\Silium.exe', '--AddCMakeWatch', 'c:\fff.txt',]) </code></pre> <p>And issue gone away. </p> <p>P.S.: its very strange that my initial code didnt work, I dont have any idea why python corrupt the command line, I think it is the python bug.</p>
python|python-3.x|subprocess
0
1,904,611
19,118,010
Capture Jython output as it happens
<p>I am developing a web app for teaching Python, and one of the issues I have to solve is how to capture the standard output from Jython interpreter, the moment it is complemented.</p> <p>Currently I capture the output in <code>StringBuilder</code> object, but this approach lets me get the output only when the code finished running:</p> <pre><code>PythonInterpreter interp = new PythonInterpreter(null, new PySystemState()); StringWriter out = new StringWriter(); interp.setOut(out); interp.exec(pyScript); String outputStr = out.toString(); </code></pre> <p>What I'd like to have, is that after the runnable code is received from the browser, the interpreter keeps running in the background. If the code is such that takes time to run, but the output is captured and stored in the database, letting an Ajax code continuously receive updates about what is outputted.</p>
<p>Man, writing my own implementation of OutputStream turned out to be the way to go. It was enough to implement just write() and flush() methods. Something along the lines of this:</p> <pre><code>public class DBOutputStream extends OutputStream { private String buffer; private DBConnClass db; public DBOutputStream (DBConnClass dbConn) { buffer = ""; db = dbConn; } public void write(int b) { byte[] bytes = new byte[1]; bytes[0] = (byte) (b &amp; 0xff); buffer = buffer + new String(bytes); if (buffer.endsWith("\n")) { buffer = buffer.substring (0, buffer.length () - 1); flush (); } } public void flush() { // Commit the buffer to db here buffer = ""; } } </code></pre> <p>I guess this is more stable than reading the OutputStream from another thread. Now it's enough to have only one thread, the one where the interpreter is running.</p>
java|python|ajax|jython
2
1,904,612
69,180,877
login bot with selenium python
<p>Hello the process of login to my bank account is very tedious because it has a randomly generated keyboard that changes letters positions all the time can I make a bot to do it in my place?? I tried it with selenium but because the letters positions change all the time on the keyboard I could not locate the letters with the xpath and the buttons don't have an id.</p>
<p>try to find the buttons by text using this:</p> <pre class="lang-py prettyprint-override"><code>def find_button_by_text(text): for i in driver.find_elements_by_tag_name('button'): if i.text == text: return i </code></pre> <p>then click it</p>
python|python-3.x|selenium
0
1,904,613
69,102,837
"for" loop for reading line from a file is not working
<p>I am trying to read file from bdata.txt. Here it is opening file properly but not start for loop, you can see attached screen where it is not printing log3 and but prining confirmation about file opening. Below is the code. Please advise</p> <pre><code>####### get file name #fname = input(&quot;Bike Data File name: &quot;) try: fh = open('bdata.txt') except: print(&quot;Not able to open file&quot;) print(fh) print(&quot;Log2&quot;) counter=0 ####### extract data for line in fh: print(&quot;Log3&quot;) counter = counter+1 print(stripped_line) fh.close() print(counter) print (&quot;**********EOF***********&quot;) </code></pre> <p><a href="https://i.stack.imgur.com/kiOSE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kiOSE.jpg" alt="enter image description here" /></a></p>
<p>I'd recommend using <code>with open() as</code> when working with files like this.</p> <pre><code>with open(&quot;bdata.txt&quot;, &quot;r&quot;) as fh: for line in fh: # perform file operations </code></pre> <p>Where does your <code>&quot;print(stripped_line)&quot;</code> variable for this come from as it doesn't seem to have been declared in your example?</p>
python|loops
2
1,904,614
69,245,280
How to print the operator as an output?
<p>I have a scenario where I want to print the a symbol.</p> <p>For example let's assume you have 2 values: <code>a=10</code> and <code>b=20</code></p> <p>Need to check <code>a</code> is greater, smaller, or equal to <code>b</code>, and then print the relationship as a symbol.</p> <p>i.e.</p> <p><code>a=10, b=20</code> → <code>&lt;</code> <br/> <code>a=10, b=5 </code> → <code>&gt;</code> <br/> <code>a=10, b=10</code> → <code>=</code> <br/></p>
<p>You can use a simple set of comparisons and a <a href="https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings" rel="nofollow noreferrer">f-string</a>:</p> <pre><code>a=10 b=20 print(f'{a} {&quot;&lt;&quot; if a&lt;b else &quot;&gt;&quot; if a&gt;b else &quot;=&quot;} {b}') </code></pre> <p>example outputs:</p> <pre><code>20 = 20 10 &lt; 20 20 &gt; 10 </code></pre>
python
1
1,904,615
69,057,163
Iterating through a file and removing reserved words
<p>I have a file that I need to read and find any reserved keywords that are used as identifiers. If a reserved keyword is found as an identifier. I need to add res_keyword. I've made a list of the reserved words:</p> <p><code>keywords =['cos','abs', 'sin','begin','end','input','output'] </code> So, if in the file, I encounter: <code>input cos;</code> I need to change it to <code>input res_cos;</code> This is what I have so far:</p> <pre><code>keywords =['cos','abs', 'sin','begin','end','input','output'] with open('filename', 'r') as file: data = file.read() for i in keywords: if i == data: data = data.replace(keywords, 'res') with open('filename', 'w') as file: file.write(data) </code></pre> <p>Edit: Here's a snippet of the input file:</p> <pre><code>input cos; cos = x + y </code></pre> <p>cos would need to be changed to <code>res_cos</code></p>
<p>Your question is vague but if I am not mistaken what I noticed is You are doing this.</p> <pre class="lang-py prettyprint-override"><code>data = data.replace(keywords, 'res') </code></pre> <p>You are using <code>keywords</code> list in the replace method, but what you should do is something like this</p> <pre class="lang-py prettyprint-override"><code>data = data.replace(i, 'res_' + i) </code></pre> <p>However, this works if the file <code>data</code> was a single string. When you do this</p> <pre class="lang-py prettyprint-override"><code>if i == data: </code></pre> <p>you are treating <code>data</code> as a single string, and this will never evaluate to true unless <code>data</code> is a single word.</p>
python|list|file
0
1,904,616
62,269,948
Executing Multiple SQL statements using execute()
<p>I am trying to do an <code>SQL injection</code> in a server of mine. I am using the command :</p> <pre><code>cursor.execute(&quot;select * from some_table&quot;) </code></pre> <p>to execute the SQL commands in my server. But is there a way to execute multiple commands using the same <code>execute()</code> function.<br> I tried :</p> <pre><code>cursor.execute(&quot;select * from some_table ; INSERT INTO ...&quot;) </code></pre> <p>DBMS is <code>mariadb</code></p>
<p><a href="https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/#StackingQueries" rel="nofollow noreferrer">Here</a> is an overview of SQL injection strategies. The one you are trying to do is called <em>stacking queries</em>. It seems that at least this strategy is prevented by most database APIs.</p> <p>You mention MariaDB which is basically more or less the same as MySQL.</p> <p>And although python is not listed explicitly, I would also assume that the python database API prevents query stacking.</p> <p><strong>Update:</strong> When you check the API of <code>execute()</code> you can see there is a parameter <code>multi</code> which defaults to <code>False</code>. As long as you don't set it to <code>True</code>, you should be safe.</p>
python|sql|mariadb|sql-injection|stacked-query
1
1,904,617
56,144,385
how to save the output (json file)of a subprocess that is in a loop
<p>this code send generates a random json file of user ids provided and btw range is also given.. </p> <p>so this code outputs 50 jsons for each user.</p> <pre><code>import faker import json from faker import Faker import random from random import randint import subprocess import json import os #subprocess.call([""]) from pprint import pprint ids= ('5cda','6cda') fake = Faker('en_US') for ind in ids: cont = [] #Overall dictionary with first and user_ids dct = {} for idx in range(50): sms = { "id":"AB-asfgw", "body": fake.text(), "mime": fake.ean(), "hashed": fake.ean(), "pid": fake.ean(), "user_id": ind, "text": fake.sentence() } cont.append(sms) dct['messages'] = cont dct['user_id'] = ind #print(dct) f_name = '{}.json'.format(ind) with open(f_name, 'w') as fp: #Save the dictionary json.dump(dct, fp, indent=4) print('saved {}'.format(f_name)) auth = "authorization: token 1324" file = "5cda.json" fd=open("5cda.json") json_content = fd.read() fd.close() subprocess.run(["grpcurl", "-plaintext","-H", auth,"-d",json_content,"-format","json","100.20.20.1:5000","api.Service/Method"]) </code></pre> <p>this loop.py code loops the first code 20 times </p> <pre><code>from datetime import datetime import faker import json from faker import Faker import random from random import randint import subprocess import json import os #subprocess.call([""]) from pprint import pprint import subprocess import sys for i in range(20): subprocess.call(['python','grploop1.py']) </code></pre> <p>i need to save the output of loop.py code for each loop. and store that json. example : we are looping the first code for 20 times in loop.py so ineed the output stored should be like 5cda1.json ........ 5cda20.json and 6cda1.json..... 6cda20.json </p> <p>here we are giving two user ids <code>ids= ('5cda','6cda')</code> so output would be total 40 json files.</p>
<p>You can save the output of called python file to a file if you write the J-son into STDOUT and in loop.py redirect the STDOUT to a file. In you "generator" file: (Of course, you should remove other prints if you don't want to get invalid J-son file.)</p> <pre><code>... dct['messages'] = cont dct['user_id'] = ind print(dct) ... </code></pre> <p>I your loop.py file:</p> <pre><code>subprocess.call(["ardbuf", "-oL", "python","grploop1.py", "&gt;", test_folder/tmp_file.json]) </code></pre>
python|python-3.x|loops|for-loop|subprocess
0
1,904,618
67,579,105
Consumer Kafka via Rest Proxy with python
<p>I am using a kafka environment via docker. It went up correctly!</p> <p>But I can't perform REST queries with my python script...</p> <p>I am trying to read all messages received on the streamer!</p> <p>Any suggestions for correction?</p> <p>Sorry for the longs outputs, I wanted to detail the problem to facilitate debugging :)</p> <p>consumer.py</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import requests import base64 import json import sys REST_PROXY_URL = 'http://localhost:8082' CONSUMER_INSTACE = 'zabbix_consumer' NAME_TOPIC = 'zabbix' def delete_consumer(BASE_URI): '''Delete the consumer''' headers = {'Accept': 'application/vnd.kafka.v2+json'} r = requests.delete(BASE_URI, headers=headers) def create_consumer(): '''Create the Consumer instance''' delete_consumer(f'{REST_PROXY_URL}/consumers/{CONSUMER_INSTACE}/instances/{CONSUMER_INSTACE}') PAYLOAD = {'format': 'json', 'name': f'{CONSUMER_INSTACE}', 'auto.offset.reset': 'earliest'} HEADERS = {'Content-Type': 'application/vnd.kafka.v2+json'} r = requests.post(f'{REST_PROXY_URL}/consumers/{CONSUMER_INSTACE}', data=json.dumps(PAYLOAD), headers=HEADERS) if r.status_code != 200: print('Status Code: ' + str(r.status_code)) print(r.text) sys.exit('Error thrown while creating consumer') return r.json()['base_uri'] def get_messages(): '''Get the messages from the consumer''' BASE_URI = create_consumer() HEADERS = {'Accept': 'application/vnd.kafka.v2+json'} r = requests.get(BASE_URI + f'/topics/{NAME_TOPIC}', headers=HEADERS, timeout=30) if r.status_code != 200: print('Status Code: ' + str(r.status_code)) print(r.text) sys.exit('Error thrown while getting message') for message in r.json(): if message['key'] is not None: print('Message Key:' + base64.b64decode(message['key'])) print('Message Value:' + base64.b64decode(message['value'])) if __name__ == '__main__': get_messages() </code></pre> <p>output</p> <pre><code>Traceback (most recent call last): File &quot;/usr/lib/python3/dist-packages/urllib3/connection.py&quot;, line 159, in _new_conn conn = connection.create_connection( File &quot;/usr/lib/python3/dist-packages/urllib3/util/connection.py&quot;, line 61, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File &quot;/usr/lib/python3.8/socket.py&quot;, line 918, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -3] Temporary failure in name resolution During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/usr/lib/python3/dist-packages/urllib3/connectionpool.py&quot;, line 665, in urlopen httplib_response = self._make_request( File &quot;/usr/lib/python3/dist-packages/urllib3/connectionpool.py&quot;, line 387, in _make_request conn.request(method, url, **httplib_request_kw) File &quot;/usr/lib/python3.8/http/client.py&quot;, line 1255, in request self._send_request(method, url, body, headers, encode_chunked) File &quot;/usr/lib/python3.8/http/client.py&quot;, line 1301, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File &quot;/usr/lib/python3.8/http/client.py&quot;, line 1250, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File &quot;/usr/lib/python3.8/http/client.py&quot;, line 1010, in _send_output self.send(msg) File &quot;/usr/lib/python3.8/http/client.py&quot;, line 950, in send self.connect() File &quot;/usr/lib/python3/dist-packages/urllib3/connection.py&quot;, line 187, in connect conn = self._new_conn() File &quot;/usr/lib/python3/dist-packages/urllib3/connection.py&quot;, line 171, in _new_conn raise NewConnectionError( urllib3.exceptions.NewConnectionError: &lt;urllib3.connection.HTTPConnection object at 0x7f0650a9be80&gt;: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/usr/lib/python3/dist-packages/requests/adapters.py&quot;, line 439, in send resp = conn.urlopen( File &quot;/usr/lib/python3/dist-packages/urllib3/connectionpool.py&quot;, line 719, in urlopen retries = retries.increment( File &quot;/usr/lib/python3/dist-packages/urllib3/util/retry.py&quot;, line 436, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='rest-proxy', port=8082): Max retries exceeded with url: /consumers/zabbix_consumer/instances/zabbix_consumer/topics/zabbix (Caused by NewConnectionError('&lt;urllib3.connection.HTTPConnection object at 0x7f0650a9be80&gt;: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;consumer.py&quot;, line 48, in &lt;module&gt; get_messages() File &quot;consumer.py&quot;, line 37, in get_messages r = requests.get(BASE_URI + f'/topics/{NAME_TOPIC}', headers=HEADERS, timeout=30) File &quot;/usr/lib/python3/dist-packages/requests/api.py&quot;, line 75, in get return request('get', url, params=params, **kwargs) File &quot;/usr/lib/python3/dist-packages/requests/api.py&quot;, line 60, in request return session.request(method=method, url=url, **kwargs) File &quot;/usr/lib/python3/dist-packages/requests/sessions.py&quot;, line 533, in request resp = self.send(prep, **send_kwargs) File &quot;/usr/lib/python3/dist-packages/requests/sessions.py&quot;, line 646, in send r = adapter.send(request, **kwargs) File &quot;/usr/lib/python3/dist-packages/requests/adapters.py&quot;, line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='rest-proxy', port=8082): Max retries exceeded with url: /consumers/zabbix_consumer/instances/zabbix_consumer/topics/zabbix (Caused by NewConnectionError('&lt;urllib3.connection.HTTPConnection object at 0x7f0650a9be80&gt;: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) </code></pre> <p>logs rest container</p> <pre><code>[2021-05-18 02:07:12,174] INFO 127.0.0.1 - - [18/May/2021:02:07:12 +0000] &quot;DELETE /consumers/zabbix_consumer/instances/zabbix_consumer HTTP/1.1&quot; 404 61 3 (io.confluent.rest-utils.requests) [2021-05-18 02:07:12,180] INFO ConsumerConfig values: allow.auto.create.topics = true auto.commit.interval.ms = 5000 auto.offset.reset = earliest bootstrap.servers = [localhost:9092] check.crcs = true client.dns.lookup = use_all_dns_ips client.id = consumer-zabbix_consumer-9 client.rack = connections.max.idle.ms = 540000 default.api.timeout.ms = 60000 enable.auto.commit = true exclude.internal.topics = true fetch.max.bytes = 52428800 fetch.max.wait.ms = 500 fetch.min.bytes = 1 group.id = zabbix_consumer group.instance.id = null heartbeat.interval.ms = 3000 interceptor.classes = [] internal.leave.group.on.close = true internal.throw.on.fetch.stable.offset.unsupported = false isolation.level = read_uncommitted key.deserializer = class org.apache.kafka.common.serialization.ByteArrayDeserializer max.partition.fetch.bytes = 1048576 max.poll.interval.ms = 300000 max.poll.records = 30 metadata.max.age.ms = 300000 metric.reporters = [] metrics.num.samples = 2 metrics.recording.level = INFO metrics.sample.window.ms = 30000 partition.assignment.strategy = [class org.apache.kafka.clients.consumer.RangeAssignor] receive.buffer.bytes = 65536 reconnect.backoff.max.ms = 1000 reconnect.backoff.ms = 50 request.timeout.ms = 30000 retry.backoff.ms = 100 sasl.client.callback.handler.class = null sasl.jaas.config = null sasl.kerberos.kinit.cmd = /usr/bin/kinit sasl.kerberos.min.time.before.relogin = 60000 sasl.kerberos.service.name = null sasl.kerberos.ticket.renew.jitter = 0.05 sasl.kerberos.ticket.renew.window.factor = 0.8 sasl.login.callback.handler.class = null sasl.login.class = null sasl.login.refresh.buffer.seconds = 300 sasl.login.refresh.min.period.seconds = 60 sasl.login.refresh.window.factor = 0.8 sasl.login.refresh.window.jitter = 0.05 sasl.mechanism = GSSAPI security.protocol = PLAINTEXT security.providers = null send.buffer.bytes = 131072 session.timeout.ms = 10000 socket.connection.setup.timeout.max.ms = 127000 socket.connection.setup.timeout.ms = 10000 ssl.cipher.suites = null ssl.enabled.protocols = [TLSv1.2, TLSv1.3] ssl.endpoint.identification.algorithm = https ssl.engine.factory.class = null ssl.key.password = null ssl.keymanager.algorithm = SunX509 ssl.keystore.certificate.chain = null ssl.keystore.key = null ssl.keystore.location = null ssl.keystore.password = null ssl.keystore.type = JKS ssl.protocol = TLSv1.3 ssl.provider = null ssl.secure.random.implementation = null ssl.trustmanager.algorithm = PKIX ssl.truststore.certificates = null ssl.truststore.location = null ssl.truststore.password = null ssl.truststore.type = JKS value.deserializer = class org.apache.kafka.common.serialization.ByteArrayDeserializer (org.apache.kafka.clients.consumer.ConsumerConfig) [2021-05-18 02:07:12,184] WARN The configuration 'metrics.context.resource.cluster.id' was supplied but isn't a known config. (org.apache.kafka.clients.consumer.ConsumerConfig) [2021-05-18 02:07:12,184] WARN The configuration 'metrics.context._namespace' was supplied but isn't a known config. (org.apache.kafka.clients.consumer.ConsumerConfig) [2021-05-18 02:07:12,184] WARN The configuration 'metrics.context.resource.version' was supplied but isn't a known config. (org.apache.kafka.clients.consumer.ConsumerConfig) [2021-05-18 02:07:12,184] WARN The configuration 'metrics.context.resource.commit.id' was supplied but isn't a known config. (org.apache.kafka.clients.consumer.ConsumerConfig) [2021-05-18 02:07:12,184] WARN The configuration 'metrics.context.resource.type' was supplied but isn't a known config. (org.apache.kafka.clients.consumer.ConsumerConfig) [2021-05-18 02:07:12,184] WARN The configuration 'schema.registry.url' was supplied but isn't a known config. (org.apache.kafka.clients.consumer.ConsumerConfig) [2021-05-18 02:07:12,184] INFO Kafka version: 6.1.1-ce (org.apache.kafka.common.utils.AppInfoParser) [2021-05-18 02:07:12,184] INFO Kafka commitId: 73deb3aeb1f8647c (org.apache.kafka.common.utils.AppInfoParser) [2021-05-18 02:07:12,184] INFO Kafka startTimeMs: 1621303632184 (org.apache.kafka.common.utils.AppInfoParser) [2021-05-18 02:07:12,185] INFO KafkaRestConfig values: access.control.allow.headers = access.control.allow.methods = access.control.allow.origin = access.control.skip.options = true advertised.listeners = [] api.endpoints.blocklist = [] api.v2.enable = true api.v3.enable = true authentication.method = NONE authentication.realm = authentication.roles = [*] authentication.skip.paths = [] bootstrap.servers = localhost:9092 client.init.timeout.ms = 60000 client.sasl.kerberos.kinit.cmd = /usr/bin/kinit client.sasl.kerberos.min.time.before.relogin = 60000 client.sasl.kerberos.service.name = client.sasl.kerberos.ticket.renew.jitter = 0.05 client.sasl.kerberos.ticket.renew.window.factor = 0.8 client.sasl.mechanism = GSSAPI client.security.protocol = PLAINTEXT client.ssl.cipher.suites = client.ssl.enabled.protocols = TLSv1.2,TLSv1.1,TLSv1 client.ssl.endpoint.identification.algorithm = client.ssl.key.password = [hidden] client.ssl.keymanager.algorithm = SunX509 client.ssl.keystore.location = client.ssl.keystore.password = [hidden] client.ssl.keystore.type = JKS client.ssl.protocol = TLS client.ssl.provider = client.ssl.trustmanager.algorithm = PKIX client.ssl.truststore.location = client.ssl.truststore.password = [hidden] client.ssl.truststore.type = JKS client.timeout.ms = 500 client.zk.session.timeout.ms = 30000 compression.enable = true confluent.resource.name.authority = consumer.instance.timeout.ms = 300000 consumer.iterator.backoff.ms = 50 consumer.iterator.timeout.ms = 1 consumer.request.max.bytes = 67108864 consumer.request.timeout.ms = 1000 consumer.threads = 50 csrf.prevention.enable = false csrf.prevention.token.endpoint = /csrf csrf.prevention.token.expiration.minutes = 30 csrf.prevention.token.max.entries = 10000 debug = false fetch.min.bytes = -1 host.name = rest-proxy id = idle.timeout.ms = 30000 kafka.rest.resource.extension.class = [] listeners = [http://localhost:8082] metric.reporters = [] metrics.jmx.prefix = kafka.rest metrics.num.samples = 2 metrics.sample.window.ms = 30000 metrics.tag.map = [] port = 8082 producer.threads = 5 request.logger.name = io.confluent.rest-utils.requests request.queue.capacity = 2147483647 request.queue.capacity.growby = 64 request.queue.capacity.init = 128 resource.extension.classes = [] response.http.headers.config = response.mediatype.default = application/json response.mediatype.preferred = [application/json, application/vnd.kafka.v2+json] rest.servlet.initializor.classes = [] schema.registry.url = http://schema-registry:8081 shutdown.graceful.ms = 1000 simpleconsumer.pool.size.max = 25 simpleconsumer.pool.timeout.ms = 1000 ssl.cipher.suites = [] ssl.client.auth = false ssl.client.authentication = NONE ssl.enabled.protocols = [] ssl.endpoint.identification.algorithm = null ssl.key.password = [hidden] ssl.keymanager.algorithm = ssl.keystore.location = ssl.keystore.password = [hidden] ssl.keystore.reload = false ssl.keystore.type = JKS ssl.keystore.watch.location = ssl.protocol = TLS ssl.provider = ssl.trustmanager.algorithm = ssl.truststore.location = ssl.truststore.password = [hidden] ssl.truststore.type = JKS thread.pool.max = 200 thread.pool.min = 8 websocket.path.prefix = /ws websocket.servlet.initializor.classes = [] zookeeper.connect = (io.confluent.kafkarest.KafkaRestConfig) [2021-05-18 02:07:12,187] INFO 127.0.0.1 - - [18/May/2021:02:07:12 +0000] &quot;POST /consumers/zabbix_consumer HTTP/1.1&quot; 200 100 10 (io.confluent.rest-utils.requests) </code></pre> <p>docker-compose</p> <pre><code>--- version: '2' services: zookeeper-1: image: confluentinc/cp-zookeeper:latest ports: - 2181:2181 environment: ZOOKEEPER_SERVER_ID: 1 ZOOKEEPER_CLIENT_PORT: 2181 ZOOKEEPER_TICK_TIME: 2000 ZOOKEEPER_INIT_LIMIT: 5 ZOOKEEPER_SYNC_LIMIT: 2 ZOOKEEPER_SERVERS: localhost:22888:23888 network_mode: host kafka-1: image: confluentinc/cp-kafka:latest ports: - 9092:9092 network_mode: host depends_on: - zookeeper-1 environment: KAFKA_BROKER_ID: 1 KAFKA_ZOOKEEPER_CONNECT: localhost:2181 KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092 schema-registry: image: confluentinc/cp-schema-registry:latest network_mode: host hostname: schema-registry container_name: schema-registry depends_on: - zookeeper-1 - kafka-1 ports: - 8081:8081 environment: SCHEMA_REGISTRY_HOST_NAME: schema-registry SCHEMA_REGISTRY_KAFKASTORE_CONNECTION_URL: localhost:2181 SCHEMA_REGISTRY_ACCESS_CONTROL_ALLOW_ORIGIN: '*' SCHEMA_REGISTRY_ACCESS_CONTROL_ALLOW_METHODS: 'GET,POST,PUT,OPTIONS' rest-proxy: image: confluentinc/cp-kafka-rest:latest network_mode: host depends_on: - zookeeper-1 - kafka-1 - schema-registry ports: - 8082:8082 hostname: rest-proxy container_name: rest-proxy environment: KAFKA_REST_HOST_NAME: rest-proxy KAFKA_REST_BOOTSTRAP_SERVERS: localhost:9092 KAFKA_REST_LISTENERS: http://localhost:8082 KAFKA_REST_SCHEMA_REGISTRY_URL: http://schema-registry:8081 </code></pre>
<p>just use kafka-python package.</p> <pre><code>pip install kafka-python </code></pre> <p>then subscribe to it like this:</p> <pre><code>from kafka import KafkaConsumer import json consumer = KafkaConsumer( &quot;your-topic&quot;, bootstrap_servers = &quot;your-kafka-server&quot;, group_id = &quot;your-consumer-group&quot;, auto_offset_reset='earliest', enable_auto_commit=True, value_deserializer=lambda x: json.loads(x.decode('utf-8'))) for record in consumer: data = record.value </code></pre> <p>just take note, that consumer groups can't have more members than number of your partitions. otherwise they'll just hang without getting any data.</p> <p>needless to say, <code>value_deserializer</code> depends on how you serialized your data when you inserted it into your topic.</p>
python|docker|rest|apache-kafka|kafka-consumer-api
1
1,904,619
19,557,801
how to make a function that check if the csv file is valid or not? (python)
<p>i have a csv file like so name: test1.csv</p> <pre><code>read_start,read_end 22,90 15,88 10,100 </code></pre> <p>test2.csv</p> <pre><code>read_start,read_end 10,100 100,10 8,10 </code></pre> <p>my question is how do i make a code that can check if all the values in read_start is less than or equal to the ones in read_end return True then return False if any value of read_start is greater than read_end</p> <p>example:</p> <blockquote> <p>validate_alignment('test1.csv')</p> </blockquote> <p>if i test this code it will returnn True</p> <p>test2.csv will be False</p> <p>this is what i have tried</p> <pre><code>import csv def validate_alignment(alignment_filename): file=open(alignment_filename) contentss=csv.reader(file) for x in contentss: if len(x)==0: return False elif len(x)!=0: if x[0]&lt;x[1]: return True else: return False </code></pre>
<pre><code>import csv def validate_alignment(alignment_filename): f = open(alignment_filename) # avoid using key word `file` f.readline() # pass the head line contents = csv.reader(f) for row in contents: if len(row) == 0: return False row = map(int, row) # cast read_start and read_end to integer if row[0] &gt; row[1]: return False return True </code></pre> <p>Let's have a test:</p> <pre><code>&gt;&gt;&gt; validate_alignment("test1.csv") True &gt;&gt;&gt; validate_alignment("test2.csv") False </code></pre> <p>I see <code>read_start,read_end</code> in the test1.csv, so I add <code>f.readline()</code> to pass the head line, if your actual data has no such line, just remove it from the code.</p>
python|csv
2
1,904,620
13,333,828
In Django's shell, how can I load ipython magic functions automatically?
<p>I want to make the following ipython commands permanent when using django shell:</p> <pre><code>%load_ext autoreload %autoreload 2 </code></pre> <p>Unfortunately, Django doesn't seem to use my global ipython config, so putting them in my default_profile doesn't seem to work. Is there any way to have these executed automatically when running django shell?</p>
<p>You can use the <a href="http://packages.python.org/django-extensions/" rel="nofollow">django extentions</a> package, which contains a <code>shell_plus</code> command. This command autoloads the models, but you also can use the <code>--notebook</code> attribute. There you can add the autoload parameter: <code>--ext django_extensions.management.notebook_extension</code>.</p> <p>See <a href="http://packages.python.org/django-extensions/shell_plus.html" rel="nofollow">here</a> for more info.</p>
django|ipython
3
1,904,621
22,129,932
How to make python sympy raise an exception when evaluates or returns Infinity?
<p>I'm using sympy python library in order to get differentials, integrals, and functions evaluation. However, when it comes to certain cases like division by 0, naturally some cases will evaluate Infinity or some will just fail.</p> <p>I've seen <code>Infinity</code> and <code>NaN</code> obtained in such error prone situations. I want to make sympy automatically raise an exception when it deals with such.</p> <p>Basically I evaluate in two different states, one very simple:</p> <pre><code>fp = fx.subs(x,p) </code></pre> <p>Where <code>fx</code> is a symbolic expression (<code>fx=S(fx)</code>) and <code>p</code> a float.</p> <p>Also I evaluate in this syntax like statements:</p> <pre><code>for x_i in xs: ys.append(float(fx.subs(x,x_i))) </code></pre> <p>Where <code>xs</code> and <code>ys</code> are lists and so <code>x_i</code> is a float.</p> <p>In first statement raising an expception would come after evaluating obtained value, and so in second case. But how to avoid doing this manually? I think is better to set sympy or python environment to <em>treat</em> <code>Infinity</code> or <code>NaN</code> especially.</p>
<p>I'm not clear what you are asking, but you can check if an expression has an infinity with <code>expr.has(oo, -oo, zoo, nan)</code>.</p>
python|exception|sympy
2
1,904,622
22,020,168
Combining dataframes of different lengths
<p>I have two different dataframes, where one is an extended version of another. (1) How do I combine the two efficiently based on if the two dataframes share the same Name? (2) also is there a way to add in four spaces for code in the stackoverflow box without typing in four spaces for each line? That can be time consuming.</p> <p><strong>more details</strong></p> <p>One is a full dataframe with multiple listings of a value (sortedregsubjdf). the other contains only unique values of that other dataframe (as it is a dataframe of network centralities) - called sortedcentralitydf</p> <p><strong>sortedregsubjdf</strong></p> <pre><code>Name Organization Year Centrality 6363 (Buz) Business And Commerce doclist[524] 2012 0.503677 8383 (Buz) Business And Commerce doclist[697] 2012 0.503677 1170 (Buz) Business And Commerce doclist[103] 2012 0.503677 1579 (Eco) Economics News doclist[140] 2013 0.500624 10979 (Gop) Provincial Government News doclist[941] 2013 0.501232 4374 (Gop) Provincial Government News doclist[368] 2013 0.501232 10988 (Npt) Not-For-Profits doclist[942] 2013 0.498810 </code></pre> <p><strong>sortedcentralitiesdf</strong> (business and commerce only appears once since it contains unique values, where sortedregsubjdf has multiple values)</p> <pre><code> Name Centrality 316 (Buz) Business And Commerce 0.503677 448 (Eco) Economics News 0.500624 499 (Gop) Provincial Government News 0.501232 366 (Npt) Not-For-Profits 0.498810 217 (Pdt) New Products And Services 0.504600 </code></pre> <p>This was my code to combine the two dataframes, but I was wondering if there was a more efficient way to do so? </p> <pre><code>for i, val in enumerate(sortedcentralitydf.Name): for x, xval in enumerate(sortedregsubjdf.Name): if val == xval: #print val, xval sortedregsubjdf.Centrality[sortedregsubjdf.Name == xval] = sortedcentralitydf.Centrality[sortedcentralitydf.Name == val].iloc[0] </code></pre>
<p>Pandas has a <code>merge</code> function. It sounds like something like this would work...</p> <pre><code>import pandas as pd merged_df = pd.merge(sortedregsubjdf, sortedcentralitiesdf, on='Name') </code></pre>
python|pandas
2
1,904,623
16,862,783
Python: Why is this string invalid?
<p><strong>SOLVED</strong></p> <p>I have this string:</p> <pre><code>' ServerAlias {hostNameshort}.* www.{hostNameshort}.*'.format(hostNameshort=hostNameshort) </code></pre> <p>But it keeps giving me a syntax error. The line is supposed to be this bash equivalent: </p> <pre><code>echo " ServerAlias ${hostOnly}.* www.${hostOnly}.*" &gt;&gt; $prjFile </code></pre> <p>Mind you the first string is a part of a myFile.write function but that isn't the issue, I can't even get the string to make enough sense for it to let me run the program. </p> <p>Traceback:</p> <pre><code> File "tomahawk_alpha.py", line 89 ' ServerAlias {hostNameshort}.* www.{hostNameshort}.*'.format(hostNameshort=hostNameshort) ^ </code></pre> <p>But no matter how I change that <code>'</code> symbol it doesn't seem to work. What am I doing wrong?</p> <p>In response to @mgilson:</p> <pre><code> myFile = open(prjFile, 'w+') myFile.write("&lt;VirtualHost 192.168.75.100:80&gt;" " ServerName www.{hostName}".format(hostName=hostName) ' ServerAlias {hostNameshort}.* www.{hostNameshort}.*'.format(hostNameshort=hostNameshort) " DocumentRoot ", prjDir, "/html" ' CustomLog "\"|/usr/sbin/cronolog /var/log/httpd/class/',prjCode,'/\{hostName}.log.%Y%m%d\" urchin"'.format(hostName=hostName) "&lt;/VirtualHost&gt;") myFile.close() </code></pre> <p>I had each line in it's own myFile.write line, but it only produced the first line and then quit. So I assumed calling it once and spacing it like that would create intended result.</p>
<p>Automatic string concatenation only works with string literals:</p> <pre><code>"foo" "bar" </code></pre> <p>results in <code>"foobar"</code></p> <p>But, the following won't work:</p> <pre><code>("{}".format("foo") "bar") </code></pre> <p>which is analogous to what you are doing. The parser sees something like this:</p> <pre><code>"{}".format("foo") "bar" </code></pre> <p>(because it joins lines where there are unterminated parenthesis) and that is clearly not valid syntax. To fix it, you need to concatenate the strings explicitly. e.g:</p> <pre><code>("{}".format("foo") + "bar") </code></pre> <p>Or use string formatting on the entire string, not just one piece of it at a time.</p>
python|syntax
4
1,904,624
43,659,249
Parse an xml file to extract element values using lxml and XPath in python
<p>I have this <code>xml</code> file and I want to extract the values associated with certain specific elements. More specifically what I want is when the element value is <code>Marks</code> then check if next element value is <code>Marks of Student</code>(They are towards the end of the in the sample xml I have shown below ). If it is then extract/print these two tags and next 3 tags(which would be Minimum,Maximum, and Mean values):</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;?mso-application progid="Excel.Sheet"?&gt; &lt;Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"&gt; &lt;DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"&gt; &lt;Version&gt;16.00&lt;/Version&gt; &lt;/DocumentProperties&gt; &lt;OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"&gt; &lt;AllowPNG/&gt; &lt;/OfficeDocumentSettings&gt; &lt;ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"&gt; &lt;WindowHeight&gt;9888&lt;/WindowHeight&gt; &lt;WindowWidth&gt;15360&lt;/WindowWidth&gt; &lt;WindowTopX&gt;0&lt;/WindowTopX&gt; &lt;WindowTopY&gt;0&lt;/WindowTopY&gt; &lt;ProtectStructure&gt;False&lt;/ProtectStructure&gt; &lt;ProtectWindows&gt;False&lt;/ProtectWindows&gt; &lt;/ExcelWorkbook&gt; &lt;Styles&gt; &lt;Style ss:ID="Default" ss:Name="Normal"&gt; &lt;Alignment ss:Vertical="Bottom"/&gt; &lt;Borders/&gt; &lt;Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="m5479808"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="m5479828"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s62"&gt; &lt;Alignment ss:Vertical="Bottom"/&gt; &lt;Borders/&gt; &lt;Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s64"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders/&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="12" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s65"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s72"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s73"&gt; &lt;Alignment ss:Horizontal="Left" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s74"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s76"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders/&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s78"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders/&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s79"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat ss:Format="###0"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s80"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat ss:Format="###0.00"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s81"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat ss:Format="#,##0"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s82"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat ss:Format="###0"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s83"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat ss:Format="###0.00"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s84"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat ss:Format="#,##0"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s85"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat ss:Format="##,##0"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s86"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat ss:Format="####0.00"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s87"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat ss:Format="##,##0"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s88"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat ss:Format="####0.00"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s89"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat ss:Format="@"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s90"&gt; &lt;Alignment ss:Horizontal="Left" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat ss:Format="@"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s91"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom" ss:WrapText="1"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat ss:Format="@"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s92"&gt; &lt;Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/&gt; &lt;Borders/&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="12" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s98"&gt; &lt;Alignment ss:Horizontal="Center" ss:Vertical="Bottom"/&gt; &lt;Borders/&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="12" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s99"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s100"&gt; &lt;Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat ss:Format="@"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s101"&gt; &lt;Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s102"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000" ss:Bold="1"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat ss:Format="@"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s103"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s104"&gt; &lt;Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat ss:Format="@"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s105"&gt; &lt;Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s106"&gt; &lt;Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/&gt; &lt;Borders&gt; &lt;Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1" ss:Color="#000000"/&gt; &lt;/Borders&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior/&gt; &lt;NumberFormat ss:Format="@"/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s108"&gt; &lt;Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/&gt; &lt;Borders/&gt; &lt;Font ss:FontName="Arial, Helvetica" ss:Size="9" ss:Color="#000000"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;Style ss:ID="s109"&gt; &lt;Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/&gt; &lt;Borders/&gt; &lt;Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/&gt; &lt;Interior ss:Color="#FFFFFF" ss:Pattern="Solid"/&gt; &lt;NumberFormat/&gt; &lt;Protection/&gt; &lt;/Style&gt; &lt;/Styles&gt; &lt;Worksheet ss:Name="Dataset Contents"&gt; &lt;Table ss:ExpandedColumnCount="6" ss:ExpandedRowCount="86" x:FullColumns="1" x:FullRows="1" ss:StyleID="s62" ss:DefaultRowHeight="14.4"&gt; &lt;Column ss:StyleID="s62" ss:Width="33.6"/&gt; &lt;Column ss:StyleID="s62" ss:Width="108"/&gt; &lt;Column ss:StyleID="s62" ss:Width="67.8" ss:Span="1"/&gt; &lt;Column ss:Index="5" ss:StyleID="s62" ss:Width="94.8"/&gt; &lt;Column ss:StyleID="s62" ss:Width="229.8"/&gt; &lt;Row ss:AutoFitHeight="0" ss:Height="31.95"&gt; &lt;Cell ss:MergeAcross="5" ss:StyleID="s64"&gt;&lt;Data ss:Type="String"&gt;Students Score Summary&lt;/Data&gt;&lt;/Cell&gt; &lt;/Row&gt; &lt;!--...bunch of &lt;Row&gt;&lt;Cell&gt;&lt;Data&gt; tags which I don't want to extract..--&gt; &lt;Cell ss:StyleID="s65"&gt;&lt;Data ss:Type="String"&gt;Variable Name&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s65"&gt;&lt;Data ss:Type="String"&gt;Variable Label&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s79"&gt;&lt;Data ss:Type="String"&gt;Minimum&amp;#10;Value&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s79"&gt;&lt;Data ss:Type="String"&gt;Maximum&amp;#10;Value&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s80"&gt;&lt;Data ss:Type="String"&gt;Mean&amp;#10;Value&lt;/Data&gt;&lt;/Cell&gt; &lt;Row ss:AutoFitHeight="0" ss:Height="15"&gt; &lt;Cell ss:StyleID="s73"&gt;&lt;Data ss:Type="String"&gt;Marks&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s73"&gt;&lt;Data ss:Type="String"&gt;Marks of Student&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s82"&gt;&lt;Data ss:Type="Number"&gt;0&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s82"&gt;&lt;Data ss:Type="Number"&gt;96&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s83"&gt;&lt;Data ss:Type="Number"&gt;65.71&lt;/Data&gt;&lt;/Cell&gt; &lt;/Row&gt; &lt;Row ss:AutoFitHeight="0" ss:Height="15"&gt; &lt;Cell ss:StyleID="s73"&gt;&lt;Data ss:Type="String"&gt;Name&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s73"&gt;&lt;Data ss:Type="String"&gt;Name of Students&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s82"&gt;&lt;Data ss:Type="Number"&gt;n/a&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s82"&gt;&lt;Data ss:Type="Number"&gt;n/a&lt;/Data&gt;&lt;/Cell&gt; &lt;Cell ss:StyleID="s83"&gt;&lt;Data ss:Type="Number"&gt;n/a&lt;/Data&gt;&lt;/Cell&gt; &lt;/Row&gt; &lt;!--...bunch of &lt;Row&gt;&lt;Cell&gt;&lt;Data&gt; tags which I don't want to extract..--&gt; . . . &lt;/Workbook&gt; </code></pre> <p>Currently I have this code where I am using <code>ElementTree</code> as to parse the xml file but it is not producing any output(it doesn't print anything).</p> <pre><code>import io import xml.etree.ElementTree tree = xml.etree.ElementTree.parse('xmlFile1.xml').getroot() parent_map = {c: p for p in tree.getiterator() for c in p} def search_data(first_text, next_text): data_with_marks = [data_node for data_node in tree.findall(".//Data") if data_node.text == first_text] for marks_elem in data_with_marks: cell_elem = parent_map[marks_elem] row_elem = parent_map[cell_elem] cell_nodes = list(row_elem) curr_index = cell_nodes.index(cell_elem) next_index = curr_index + 1 next_data_node = next(iter(cell_nodes[next_index])) if next_data_node.text == next_text: return [next(iter(cell_node)) for cell_node in cell_nodes[curr_index:curr_index + 6]] return [] if __name__ == '__main__': for node in search_data("Marks", "Marks of Student"): print(node.text) </code></pre> <p>I am trying to look for <code>lxml</code> and <code>XPath</code> but don't know how to do that. How can I modify my current code to use <code>lxml</code> and <code>XPath</code> to parse the <code>xml</code> file and get the output I want?</p>
<p>Here is a way to extract the wanted information with ElementTree:</p> <pre><code>from xml.etree import ElementTree as ET NSMAP = {"ss": "urn:schemas-microsoft-com:office:spreadsheet"} tree = ET.parse("xmlFile1.xml") # Find all Row elements rows = tree.findall(".//ss:Row", NSMAP) # For each Row, get all Data 'grandchildren' for row in rows: data = row.findall("ss:Cell/ss:Data", NSMAP) if data and len(data) == 5: # If first two Data elements are what we want, print out all Data element values if data[0].text == "Marks" and data[1].text == "Marks of Student": for d in data: print (d.text) </code></pre> <p>Output:</p> <pre><code>Marks Marks of Student 0 96 65.71 </code></pre> <p>The default namespace is <code>urn:schemas-microsoft-com:office:spreadsheet</code>, and the elements you are interested in are in this namespace. That's why we need to use the <code>NSMAP</code> dictionary. See <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces" rel="nofollow noreferrer">https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces</a>.</p>
python|xml|xpath|xml-parsing|lxml
2
1,904,625
43,843,481
Counting recurrences in a nested list
<p>I have a nested list that contains 2 names and 2 ages respectively. I need to write a function that looks through the list and counts the number of times the name appears. The list looks like this: </p> <pre><code>L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'], ['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']] </code></pre> <p>So this function would count that James is in the list twice, Alan twice, and the rest of the names once.</p>
<p>To count things, I'd suggest a <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer"><code>Counter</code></a>:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'], ['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']] &gt;&gt;&gt; Counter(name for sub_list in L for name in sub_list[:2]) Counter({'James': 2, 'Alan': 2, 'Phil': 1, 'Bill': 1, 'Hillary': 1, 'Henry': 1}) </code></pre>
python|list|count|nested
3
1,904,626
53,518,025
Keeping container alive with Docker Python SDK
<p>I am using the Docker Sdk for Python to run my container.</p> <p>I am trying to start a docker container, and then run a command using the api exec_run (I need the exit code). The exec_run needs to be executed on a started container.</p> <p>This is my code:</p> <pre><code>import docker client = docker.from_env() container = client.containers.run('e7d8452ce5f5', command="echo starting", detach=True) container.exec_run("echo execute command") </code></pre> <p>This raises an exception:</p> <pre><code>docker.errors.APIError: 409 Client Error: Conflict ("Container b65acd40f589819f490564dcb4e25f3055d85712cb7b2834ede5f2c4d57f2da6 is not running") </code></pre> <p>I tried running with no command when invoking client.containers.run, same exception..</p> <p>Seems the container exists when the command is finished, even though in their documentation it is stated that the command run with detach=True is same as the cli docker run -d (when using docker run -d the container stays alive)</p> <p>Any ideas on how to keep the container alive in order to call exec_run on it?</p>
<p>When you use containers.run() method to start a ontainer,you should use <strong>tty</strong> parameter and set <strong>tty=True</strong> and then it will keep the container alive.</p> <pre><code>import docker client = docker.from_env() container = client.containers.run('xxxx', command="/bin/bash", tty=True,detach=True) </code></pre>
python|docker
2
1,904,627
71,165,455
Finding subsentences from one singular sentence
<p>I am trying to create a list of possible subsentences from a single given sentence in Python, but cannot figure out how to do so.</p> <p>For example:</p> <pre><code>sentence_1 = 'the dog jumped around' </code></pre> <p>and I want to split it into:</p> <pre><code>['the', 'the dog' 'dog jumped' 'jumped around' 'the dog jumped' 'dog jumped around' 'the dog jumped around' ] </code></pre>
<p>To have all subsentence of at least 2 words:</p> <pre><code>sentence_1 = 'the dog jumped around' words = sentence_1.split() data = [] for i in range(len(words)): for j in range(i + 2, len(words) + 1): data.append(&quot; &quot;.join(words[i:j])) print(data) </code></pre> <p>As you also want the first word:</p> <pre><code>data.append(words[0]) </code></pre> <p><strong>Output:</strong></p> <pre><code>['the', 'the dog', 'the dog jumped', 'the dog jumped around', 'dog jumped', 'dog jumped around', 'jumped around'] </code></pre> <p>I have to admit I don't really understand why <code>'the'</code> has to be in the list, but not <code>'dog'</code>, <code>'jumped'</code> nor <code>'around'</code></p> <hr /> <p>To have <em><strong>all</strong></em> subsentences:</p> <pre><code>sentence_1 = 'the dog jumped around' words = sentence_1.split() data = [] for i in range(len(words)): for j in range(i + 1, len(words) + 1): data.append(&quot; &quot;.join(words[i:j])) print(data) </code></pre> <p><strong>Output:</strong></p> <pre><code>['the', 'the dog', 'the dog jumped', 'the dog jumped around', 'dog', 'dog jumped', 'dog jumped around', 'jumped', 'jumped around', 'around'] </code></pre>
python
1
1,904,628
9,107,920
MLM downline distribution count
<p>I make my first MLM software and I think I managed to code how to get the points from the downline even though it is a recursive problem I didn't use recursion and I might refactor to a recursive version if that seems better. With our system, the level of a distributor is measured i number of silvers and for each product that gets sold the promotion/bonus/score/points works upline so if Bob is the sponsor of Alice and Alice makes a purchase then Bob will get points measured in number of silvers for that purchase. I added a business function to my user class:</p> <pre><code>def this_month_non_manager_silver(self): silver = 0 today = date.today() timeline = date(today.year, today.month, 1) downline = User.query(User.sponsor == self._key).fetch() distributor = self while distributor.has_downline(): downline = User.query(User.sponsor == distributor.key).fetch() for person in downline: orders = model.Order.all().filter('buyer_id =' , person.key.id()).filter('created &gt;' , timeline).filter('status =', 'PAID').fetch(999999) for order in orders: for idx,item in enumerate(order.items): purchase = model.Item.get_by_id(long(item.id())) amount = int(order.amounts[idx]) silver = silver + amount*purchase.silver/1000.000 distributor = person return silver </code></pre> <p>What might be to do is now just a % on the silver according to the depth of the order. The code actually output the correct result for an order downline but I didn't yet test it extensively and I wonder if you think the code looks strange and if I have thought of everything since the models are somewhat complicated / advanced. The user class is from webapp2 and I could use a subclass but I didn't have time to do that so I just put in the method to the user class that's there and now I can call it from Jinja2 like <code>{{user.this_month_non_manager_silver}}</code> </p> <p>Recursion might to be right way to do this but isn't my solution still OK and I can move on and keep this code for now or do you think it is not acceptable?</p> <p>Thanks for any constructive criticism. </p>
<p>The main problem I see here is that you're essentially trying to do a breadth-first search (you look at all the users who are below the distributor, then look at all of the users below those distributors, etc etc), but each time the while loop loops you're only looking at the users below the last distributor.</p> <p>If we break down the important parts into something python-ish, you get this:</p> <pre><code>distributor=self while distributor.has_downline(): for person in distributor.downline: distributor = person </code></pre> <p>As you can see, the value of distributor after the first set of downlines are accessed is the last distributor in the user's downline. Then the next time the for loop is run, you're only looking at the last distributor's downline.</p> <p>Traditionally a tree-walking algorithm is either recursive or loop-based with a stack. Generally you will choose one or the other based on memory constraints. To keep the solution iterative, you'd need to rewrite the above python-ish code like this:</p> <pre><code>downlinestack = [] distributor=self downlinestack += distributor.downline while downlinestack: downline = downlinestack.pop() for person in downline: downlinestack.append(person.downline) </code></pre>
python|google-app-engine|recursion|python-2.7|webapp2
2
1,904,629
55,285,605
Acumos: docker container unable to find files
<p>I am trying to test a model that I onboarded to the Acumos platform (with python client). Running the image in docker fails with this error :</p> <p>File "h5py/h5f.pyx", line 85, in h5py.h5f.open OSError: Unable to open file (unable to open file: name = 'data/keras/ticketsModel/model.hdf5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)</p> <p>My code looks like that :</p> <pre><code>from acumos.session import AcumosSession from acumos.modeling import Model, List, create_dataframe from tensorflow.python.keras.models import load_model # This version tells me : unable to open file: name = 'data/keras/ticketsModel/model.hdf5' #def classify_ticket(inText: str) -&gt; str: # current_model = load_model('data/keras/ticketsModel/model.hdf5') # return current_model.predict(inText) # This version tells me : NotImplementedError: numpy() is only available when eager execution is enabled. current_model = load_model('data/keras/ticketsModel/model.hdf5') def classify_ticket(inText: str) -&gt; str: return current_model.predict(inText) model = Model(classify=classify_ticket) session = AcumosSession() session.dump(model,'ticket_classification','acumos_out') </code></pre> <p>Any help is greatly appreciated !</p>
<p>The <code>acumos</code> library currently serializes models on behalf of users so that it can bundle objects in a portable manner while minimizing developer effort. An option to provide custom serialization logic may be added in the future however.</p> <p>The solution to your problem should be to load your model above the function definition, e.g.:</p> <pre><code>current_model = load_model('data/keras/ticketsModel/model.hdf5') def classify_ticket(inText: str) -&gt; str: return current_model.predict(inText) </code></pre>
python|acumos
0
1,904,630
55,515,596
Trying to make a simple menu with tkinter but returns "Display is not capable of DPMS"
<p>I am very noob and I need help please.</p> <p>Here's my code:</p> <pre><code>from tkinter import * root = Tk() root.geometry('500x500') def callback() : print ("click!") b = Button(root, text="OK", command=callback) b.pack() mainloop() </code></pre>
<p>Try This:</p> <pre><code>from Tkinter import * import tkMessageBox root = Tk() root.geometry('200x60') root.title('Test Application') def notify(): tkMessageBox.showwarning('Notification', 'Display is not capable of DPMS!') b1 = Button(root, text="Run!", command=notify) b1.pack() root.mainloop() </code></pre>
python|python-3.x|tkinter
1
1,904,631
47,778,449
How to save errors from Jupyter Notebook cells to a file?
<p>I am trying to save all output (stdout and all errors) of a cell to a file. To save stdout, I am using the following:</p> <pre><code>import sys old_stdout = sys.stdout sys.stdout = open('test.txt', 'w') print("Hello World! ") </code></pre> <p>In this case, the output is not displayed and gets saved in the file as expected. To save errors, I used:</p> <pre><code>#Doesn't work sys.stderr = open('error.txt','w') print(a) #Should raise NameError </code></pre> <p>When I run this cell, I get the error in the notebook, and not in the file as expected:</p> <pre><code>--------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-5-de3efd936845&gt; in &lt;module&gt;() 1 #Doesn't work ----&gt; 2 sys.stderr = open('error.txt','w') 3 print("Test") 4 print(a) NameError: name 'sys' is not defined </code></pre> <p>I would like this saved in a file and not shown in the notebook. What is the correct code for this?</p>
<p>I <em>think</em> that the problem here is that IPython kernels spawned for the notebook use a <a href="https://github.com/ipython/ipykernel/blob/bec1a43f7b192895b0b9ca1f5ee1b89b9ff4643b/ipykernel/zmqshell.py#L440" rel="nofollow noreferrer">ZMQInteractiveShell</a> instance, which catches the errors before they make it to stderr, in order to send the error information to the various potential frontends (consoles, jupyter notebooks, etc). See <a href="https://github.com/ipython/ipykernel/blob/7d91110f8f471dbdd3ea65099abcb96a99179557/ipykernel/ipkernel.py#L397-L413" rel="nofollow noreferrer">ipykernel/ipkernel.py#L397-L413</a> for the code which catches exceptions, then <a href="https://github.com/ipython/ipython/blob/65739c0e8bd2b2184a63643358803c57ae7aed42/IPython/core/interactiveshell.py#L1873-L1879" rel="nofollow noreferrer">InteactiveShell._showtraceback</a> for the base implementation (print to <code>sys.stderr</code>), and <a href="https://github.com/ipython/ipykernel/blob/bec1a43f7b192895b0b9ca1f5ee1b89b9ff4643b/ipykernel/zmqshell.py#L535-L558" rel="nofollow noreferrer">ZMQInteractiveShell._showtraceback</a> for that used by notebook kernels (send stderr-channel messages over zmq to frontends).</p> <p>If you're not bothered about getting exact stderr output, you could take advantage of IPython's <a href="https://github.com/ipython/ipykernel/blob/7d91110f8f471dbdd3ea65099abcb96a99179557/ipykernel/ipkernel.py#L238" rel="nofollow noreferrer">existing error logging</a>, which logs errors to a <code>StreamHandler</code> with the prefix <code>"Exception in execute request:"</code>. To use this, set the ipython log level, and alter the provided handler's stream:</p> <pre><code>import logging import sys my_stderr = sys.stderr = open('errors.txt', 'w') # redirect stderr to file get_ipython().log.handlers[0].stream = my_stderr # log errors to new stderr get_ipython().log.setLevel(logging.INFO) # errors are logged at info level </code></pre> <p>Alternatively, to get your shell errors to print directly to a file without alteration, you can monkey-patch the <code>_showtraceback</code> method to print traceback to file as well as zmq message queues:</p> <pre><code>import sys import types # ensure we don't do this patch twice if not hasattr(get_ipython(), '_showtraceback_orig'): my_stderr = sys.stderr = open('errors.txt', 'w') # redirect stderr to file # monkeypatch! get_ipython()._showtraceback_orig = get_ipython()._showtraceback def _showtraceback(self, etype, evalue, stb): my_stderr.write(self.InteractiveTB.stb2text(stb) + '\n') my_stderr.flush() # make sure we write *now* self._showtraceback_orig(etype, evalue, stb) get_ipython()._showtraceback = types.MethodType(_showtraceback, get_ipython()) </code></pre>
python|python-2.7|jupyter-notebook
4
1,904,632
47,663,874
Is there a way to stop a tkinter class object from opening until the button is opened
<p>I have a little problem with my code. I am writing multiples classes with different GUI interfaces as a project. However, every time I import those classes the GUI window automatically opens the window and I want the window to open only when a button is clicked.</p> <pre><code>from FinalProject import addFlight from FinalProject import reserveFlight class ex: def __init__(self,win): self.win = win ... ... def mainButtons(self): look = Button(self.win, text="Add New Flight",command=lambda: self.reserveMenu(1)) look.place(relx="0.2", rely="0.3") res = Button(self.win, text="Book A Flight",command=lambda: self.reserveMenu(2)) res.place(relx="0.4", rely="0.3") ... ... def reserveMenu(self, options): if options == 1: self.flight = Toplevel(self.win) self.flMenu = addFlight.AddFlights(self.flight) self.flMenu.addingFlight() # call(["python","addFlight.py"]) if options == 2: pass # self.flight = Toplevel(self.win) # self.flMenu = reserveFlight.ReserveFlights(self.flight) # self.flMenu.reserve() # call(["python","reserveFlight.py"]) ... ... </code></pre> <p>The "reserveMenu" function works fine but is there way to suppress those import statements or at least prevent the windows from opening until the button is clicked. </p> <p>I know there are other methods of opening my python code but this <b>HAS</b> to be done using <b>CLASSES</b>. Trust me I have found way easier methods of doing this. FYI, there is more code but I only copied the more important parts. </p>
<p>Instead of using a method you could define your reserve option windows as classes, <code>ReserveAdd</code>, <code>ReserveBook</code>, that inherit from <code>tkinter.Toplevel</code>. And all a button would do is to call them. Here's an example:</p> <pre><code>import tkinter as tk root = tk.Tk() class ReserveAdd(tk.Toplevel): def __init__(self, master): super().__init__(master) self.master = master tk.Label(self, text="This is ReserveAdd window.").pack() class ReserveBook(tk.Toplevel): def __init__(self, master): super().__init__(master) self.master = master tk.Label(self, text="This is ReserveBook window.").pack() def res_one(): ReserveAdd(root) def res_two(): ReserveBook(root) tk.Button(root, text="Reserve Option 1", command=res_one).pack() tk.Button(root, text="Reserve Option 2", command=res_two).pack() root.mainloop() </code></pre> <p>In the above example <code>Reserve Option 1</code> calls an instance of <code>ReserveAdd</code> class whereas <code>Reserve Option 2</code> calls an instance of a <code>ReserveBook</code> class.</p> <p>I'd define a single method for buttons but that's not exactly the scope here.</p>
python-3.x|user-interface|tkinter|python-3.6
0
1,904,633
34,377,278
How do I call a function?
<p>I am trying to make a program that solves math equations. I want it to ask what type of question would you like to solve, then based on the answer, it then directs you to a function that I created. the function will ask you the values of some variables, and it will then solve the question.</p> <pre><code>What_do_you_need = raw_input("Which equation would you like to use?") if What_do_you_need == "find_Y_value": slope = int(raw_input("Enter the slope")) X = int(raw_input("Enter the X coordinate")) Y_int = int(raw_input("Enter the Y intercept")) import find_Y_value def find_Y_value(slope, X, Y_int): Y = (slope * X) + Y_int print(Y) def find_Y_int(Y, slope, X): Y_int = (slope * X) - Y print(Y_int) def find_X_value(Y, slope, Y_int): X_value = (Y-Y_int)/slope print(X_value) def Slope_from_Slope_int(Y, X, Y_int): slope = (Y-Y_int)/X print(slope) def Slope_from_Coordinates(X1, X2, Y1, Y2): slope1 = (Y2 - Y1)/(X2 - X1) print(slope1) </code></pre>
<p>If I properly understand your goal, to call the function you would replace <code>import find_Y_value</code> with:</p> <pre><code>find_Y_value(slope, X, Y_int) </code></pre> <p>and move the definitions above the place where you call them, or they will not have been defined yet.</p>
python|function
0
1,904,634
7,186,543
how to send a "Ctrl+Break" to a subprocess via pid or handler
<pre><code>import subprocess proc = subprocess.Popen(['c:\windows\system32\ping.exe','127.0.0.1', '-t'],stdout=subprocess.PIPE) while True: line = proc.stdout.readline() print "ping result:", line.rstrip() #sendkey("Ctrl+Break", proc) # i need this here, this is not for terminate the process but to print a statistics result for the ping result. </code></pre> <p>If someone know how to do it, please share with me, thanks!</p>
<p>Windows? Try this:</p> <pre><code>import signal proc.send_signal(signal.SIGBREAK) </code></pre> <p>If you meant a signal interrupt (<code>kill -2</code>)</p> <pre><code>import signal proc.send_signal(signal.SIGINT) </code></pre>
python|controls|sendkeys
2
1,904,635
52,251,199
Low validation accuracy with good training accuracy - keras imagedatagenerator flow_from_directory categorical classification
<p>I am trying to classify the Kaggle 10k dog images to 120 breeds using Keras and ResNet50. Due to memory constraints at Kaggle (14gb ram) - I have to use the ImageDataGenerator that feeds the images to the model and also allows data augmentation - in real time.</p> <p>The base convoluted ResNet50 model:</p> <pre><code>conv_base = ResNet50(weights='imagenet', include_top=False, input_shape=(224,224, 3)) </code></pre> <p>My model:</p> <pre><code>model = models.Sequential() model.add(conv_base) model.add(layers.Flatten()) model.add(layers.Dense(256, activation='relu')) model.add(layers.Dropout(0.5)) model.add(layers.Dense(120, activation='softmax')) </code></pre> <p>Making sure that only my last added layers are trainable - so the ResNet50 original weights will not be modified in the training process and compiling model:</p> <pre><code>conv_base.trainable = False model.compile(optimizer=optimizers.Adam(), loss='categorical_crossentropy',metrics=['accuracy']) Num trainable weights BEFORE freezing the conv base: 216 Num trainable weights AFTER freezing the conv base: 4 </code></pre> <p>And the final model summary:</p> <pre><code>_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= resnet50 (Model) (None, 1, 1, 2048) 23587712 _________________________________________________________________ flatten_1 (Flatten) (None, 2048) 0 _________________________________________________________________ dense_1 (Dense) (None, 256) 524544 _________________________________________________________________ dropout_1 (Dropout) (None, 256) 0 _________________________________________________________________ dense_2 (Dense) (None, 120) 30840 ================================================================= Total params: 24,143,096 Trainable params: 555,384 Non-trainable params: 23,587,712 _________________________________________________________________ </code></pre> <p>The train and validation directories have each, 120 sub directories - one for each dog breed. In these folders are images of dogs. Keras is supposed to use these directories to get the correct label for each image: so an image from a "beagle" sub dir is classified automatically by Keras - no need for one-hot-encoding or anything like that. </p> <pre><code>train_dir = '../input/dogs-separated/train_dir/train_dir/' validation_dir = '../input/dogs-separated/validation_dir/validation_dir/' train_datagen = ImageDataGenerator(rescale=1./255) test_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( train_dir,target_size=(224, 224),batch_size=20, shuffle=True) validation_generator = test_datagen.flow_from_directory( validation_dir,target_size=(224, 224),batch_size=20, shuffle=True) Found 8185 images belonging to 120 classes. Found 2037 images belonging to 120 classes. </code></pre> <p>Just to make sure these classes are right and in the right order I've compared their train_generator.class_indices and validation_generator.class_indices - and they are the same. Train the model:</p> <pre><code>history = model.fit_generator(train_generator, steps_per_epoch=8185 // 20,epochs=10, validation_data=validation_generator, validation_steps=2037 // 20) </code></pre> <p>Note in the charts below, that while training accuracy improves as expected - the validation sets quickly around 0.008 which is 1/120...RANDOM prediction ?!</p> <p><a href="https://i.stack.imgur.com/jbCK5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jbCK5.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/Y0Y0Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y0Y0Q.png" alt="enter image description here"></a></p> <p>I've also replaced the train with validation and vice versa - and got the same issue: training accuracy improving while the validation accuracy got stuck on approx 0.008 = 1/120.</p> <p>Any thoughts would be appreciated.</p>
<p>I've played with the <strong>batch size</strong> and found batch_size = 120 (the number of directories in the train as well as the valid directories) to eliminate the above issue. Now I can happily employ data augmentation techniques without crashing my Kaggle kernel on memory issues. Still I wonder...</p> <p><em>How is Keras ImageDataGenerator sampling images from a directory when in categorical classification mode - depth or breadth wise ?</em></p> <p>If depth wise - than with a batch size of 20 it will go thru the FIRST directory of say 100 photos (five times), and then move to the next directory, do it in batches of 20, move to the next dir... Or is it breadthwise ?</p> <p>Breadthwise - the initial batch of 20 will be ONE photo from each of the first 20 directories and then the next 20 directories ? I couldn't find in the documentation how is Keras ImageDataGenerator working with batches when used with <strong>flow_from _directory</strong> and fit_generator.</p>
python|image|keras
0
1,904,636
16,237,719
python ctypes messagebox appears under all programs
<p>I'm new in python and I needed a messagebox. I used ctypes but it opens the message box under all other programs. how can I make it to be <strong>above</strong> all programs??</p> <pre><code>import ctypes def run(x=0): STOP = False x += 5 MessageBox = ctypes.windll.user32.MessageBoxA reply = MessageBox(None, 'text', 'title', 1) if reply == 1 and not STOP: threading.Timer(3, run).start() else: STOP = True; </code></pre>
<p>You are passing <code>NULL</code> for the <code>hWnd</code> parameter of <code>MessageBox</code>. From the <a href="http://msdn.microsoft.com/en-gb/library/windows/desktop/ms645505.aspx" rel="nofollow">documentation</a>:</p> <blockquote> <p>A handle to the owner window of the message box to be created. If this parameter is NULL, the message box has no owner window.</p> </blockquote> <p>So, the message box has no owner window. Which means that it may well appear behind other windows. Ideally you should pass the window handle of an appropriate owner window in your application. Owned windows always appear above their owners. That's far and away the most normal way to control which windows appear on top of other windows.</p> <p>However, I suspect that you may find it hard to come up with such a window handle. In which case you may find that including the <code>MB_TOPMOST</code> flag in the <code>uType</code> parameter, parameter number 4, meets your needs.</p> <p>It's hard to be quite sure what you exact needs are though, because what you ask for is demonstrably impossible to achieve. You asked that the window</p> <blockquote> <p>be above all programs</p> </blockquote> <p>Well, that's clearly impossible, as can be proved by demonstrating a contradiction. Suppose that your window showed itself above all other windows. If your window could do that, so could another window. And clearly you cannot have two different windows that show above all other windows.</p>
python|ctypes|messagebox
3
1,904,637
32,071,231
Python 2.7, AT command response, strange HEX
<p>From doing a USD AT command I get the following response:</p> <blockquote> <p>00520030002E00300030002000610069007200740069006D0065002C0020003000200053004D005300200061006E0064002000300020004D00420020006F006600200064006100740061002E0020004400690061006C0020002A003100340031002A0031002300200066006F0072002000640065007400610069006C0073002E00200057006F005700210020005500730065002000520037002000610069007200740069006D006500200074006F00200067006500740020005200350035002B00310030004D0042002E004400690061006C0020002A003100330030002A0035003000310023</p> </blockquote> <p>Which produces:</p> <blockquote> <p>' R 0 . 0 0 a i r t i m e , 0 S M S a n d 0 M B o f d a t a . D i a l * 1 4 1 * 1 # f o r d e t a i l s . W o W ! U s e R 7 a i r t i m e t o g e t R 5 5 + 1 0 M B . D i a l * 1 3 0 * 5 0 1 #'</p> </blockquote> <p>After running: </p> <pre><code>ascii = rawHex.decode("hex") </code></pre> <p>I figured out that there is an additional null character after each 'valid' hex digit. So instead of 52 it produces 5200</p> <p>I did manage to remove the 00 after every valid hex digit by doing:</p> <pre><code>rawHex = ''.join( [ rawHex[i:i+2] for i in range(2,len(rawHex),4)] ) ascii = rawHex.decode("hex") </code></pre> <p>Which produces the correct result:</p> <blockquote> <p>'R0.00 airtime, 0 SMS and 0 MB of data. Dial *141*1# for details. WoW! Use R7 airtime to get R55+10MB.Dial *130*501#'</p> </blockquote> <p>So my question: I do not know why it does this, is this a standard that I am not aware of yet?</p>
<p>You appear to have <a href="https://en.wikipedia.org/wiki/UTF-16" rel="nofollow">UTF-16</a>-encoded data, in big-endian order, which uses 2 bytes per character encoded. For anything in the Latin-1 range (Unicode codepoints U+0000 through to U+00FF) the most significant byte is always 00; your sample data consists of characters in the ASCII range only but I'd not count on that always being the case.</p> <p>You can decode this directly without removing the null bytes by using the <code>utf-16-be</code> codec:</p> <pre><code>&gt;&gt;&gt; rawhex = '00520030002E00300030002000610069007200740069006D0065002C0020003000200053004D005300200061006E0064002000300020004D00420020006F006600200064006100740061002E0020004400690061006C0020002A003100340031002A0031002300200066006F0072002000640065007400610069006C0073002E00200057006F005700210020005500730065002000520037002000610069007200740069006D006500200074006F00200067006500740020005200350035002B00310030004D0042002E004400690061006C0020002A003100330030002A0035003000310023' &gt;&gt;&gt; rawhex.decode('hex') '\x00R\x000\x00.\x000\x000\x00 \x00a\x00i\x00r\x00t\x00i\x00m\x00e\x00,\x00 \x000\x00 \x00S\x00M\x00S\x00 \x00a\x00n\x00d\x00 \x000\x00 \x00M\x00B\x00 \x00o\x00f\x00 \x00d\x00a\x00t\x00a\x00.\x00 \x00D\x00i\x00a\x00l\x00 \x00*\x001\x004\x001\x00*\x001\x00#\x00 \x00f\x00o\x00r\x00 \x00d\x00e\x00t\x00a\x00i\x00l\x00s\x00.\x00 \x00W\x00o\x00W\x00!\x00 \x00U\x00s\x00e\x00 \x00R\x007\x00 \x00a\x00i\x00r\x00t\x00i\x00m\x00e\x00 \x00t\x00o\x00 \x00g\x00e\x00t\x00 \x00R\x005\x005\x00+\x001\x000\x00M\x00B\x00.\x00D\x00i\x00a\x00l\x00 \x00*\x001\x003\x000\x00*\x005\x000\x001\x00#' &gt;&gt;&gt; rawhex.decode('hex').decode('utf-16-be') u'R0.00 airtime, 0 SMS and 0 MB of data. Dial *141*1# for details. WoW! Use R7 airtime to get R55+10MB.Dial *130*501#' </code></pre> <p>In most contexts, UTF-16-encoded data includes a <a href="https://en.wikipedia.org/wiki/Byte_order_mark" rel="nofollow"><em>Byte Order Mark</em> (BOM)</a> at the start, which is really just the <a href="https://codepoints.net/U+FEFF" rel="nofollow">U+FEFF ZERO WIDTH NO-BREAK SPACE</a> character, which tells decoders what byte order to use when decoding. When printed the character is essentially invisible.</p> <p>You may have omitted it here, but if your data stream started with the bytes FE FF then that would definitely confirm you have big-endian UTF-16 data. If the stream started with FF FE then you have <em>little</em>-endian UTF-16 (byte order swapped) and also cut your sample at the wrong boundary here.</p> <p>If the BOM is there then you don't have to specify the byte order manually; decoding with <code>utf-16</code> suffices:</p> <pre><code>&gt;&gt;&gt; ('FEFF' + rawhex).decode('hex').decode('utf-16') u'R0.00 airtime, 0 SMS and 0 MB of data. Dial *141*1# for details. WoW! Use R7 airtime to get R55+10MB.Dial *130*501#' </code></pre>
python|python-2.7|pyserial|at-command
1
1,904,638
32,051,859
Not able to load Django template
<p>Am having a strange issue here. I have two templates in my app named app. <code>base.html</code> and <code>view.html</code>. I have a button in my base.html page to navigate to my view.html. The problem am facing is when I am clicking the button in my base.html page the view.html page is not displaying(even though in the urls changed accordingly). Can some help me identify the problem? Thanks in advance. </p> <p>My Folders and files:</p> <p><a href="https://i.stack.imgur.com/30ddY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/30ddY.png" alt="enter image description here"></a></p> <p>And my view.py</p> <pre><code>from django.shortcuts import render from django.views.generic.detail import DetailView from django.utils import timezone from django.views import generic def home(request): return render(request, "base.html", {}) class DetailView(generic.DetailView): template_name = 'app/view.html' </code></pre> <p>and urls.py</p> <pre><code>from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from app.views import DetailView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'$', 'app.views.home', name='home'), url(r'^view/', DetailView.as_view(), name='view'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_URL) </code></pre> <p>and my button in base.html</p> <pre><code>{% load staticfiles %} {#&lt;img src="{% static "my_app/myexample.jpg" %}" alt="My image"/&gt;#} &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --&gt; &lt;meta name="description" content=""&gt; &lt;meta name="author" content=""&gt; &lt;link rel="icon" href="../../favicon.ico"&gt; &lt;title&gt;Parasol.&lt;/title&gt; &lt;link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"&gt; &lt;link href="{% static 'css/navbar-static-top.css' %}" rel="stylesheet"&gt; &lt;link href="{% static 'css/style.css' %}" rel="stylesheet"&gt; &lt;link href="navbar-static-top.css" rel="stylesheet"&gt; &lt;script src="../../assets/js/ie-emulation-modes-warning.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;nav class="navbar navbar-default navbar-static-top"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="#"&gt;Parasol.&lt;/a&gt; &lt;/div&gt; &lt;div id="navbar" class="navbar-collapse collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#about"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"&gt;Photos &lt;span class="caret"&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li&gt;&lt;a href="../navbar/"&gt;Timeline&lt;/a&gt;&lt;/li&gt; &lt;li class="active"&gt;&lt;a href="./"&gt;Quotes&lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="../navbar-fixed-top/"&gt;Friends&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/nav&gt; &lt;div class="container"&gt; &lt;div class="jumbotron"&gt; &lt;h1&gt;Heading Heading&lt;/h1&gt; &lt;p&gt; &lt;a href="{% url 'view' %}" class="btn btn-lg btn-primary"&gt;Let's go&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="../../dist/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;!-- IE10 viewport hack for Surface/desktop Windows 8 bug --&gt; &lt;script src="../../assets/js/ie10-viewport-bug-workaround.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and view.html</p> <pre><code>{% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Chameleon Guys&lt;/title&gt; &lt;/head&gt; &lt;body&gt; Its just for you dudes!! &lt;/body&gt; &lt;/html&gt; </code></pre> <h2>Edited</h2> <p>New directory as per Rekwan:</p> <p><a href="https://i.stack.imgur.com/j3N8j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j3N8j.png" alt="enter image description here"></a></p>
<p>I think the problem has to do with the location of your templates. Templates should be found in <code>templates/appname/templates/view.html</code>. They should them be called by <code>templates/view.html</code>. In the snippets you have provided above you have <code>templates/appname/view.html</code>.</p> <p>Furthermore, you have imported <code>DetailView</code> then proceeded to name your view <code>DetailView</code>. I think this overrides the imported class. Name your view to something other than the generics to avoid potential bugs.</p> <p>Hope that helps.</p>
python|django|django-templates|django-views|django-generic-views
0
1,904,639
31,768,464
Confidence Interval for t-test (difference between means) in Python
<p>I am looking for a quick way to get the t-test confidence interval in Python for the difference between means. Similar to this in R:</p> <pre><code>X1 &lt;- rnorm(n = 10, mean = 50, sd = 10) X2 &lt;- rnorm(n = 200, mean = 35, sd = 14) # the scenario is similar to my data t_res &lt;- t.test(X1, X2, alternative = 'two.sided', var.equal = FALSE) t_res </code></pre> <p>Out:</p> <pre><code> Welch Two Sample t-test data: X1 and X2 t = 1.6585, df = 10.036, p-value = 0.1281 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -2.539749 17.355816 sample estimates: mean of x mean of y 43.20514 35.79711 </code></pre> <p>Next:</p> <pre><code>&gt;&gt; print(c(t_res$conf.int[1], t_res$conf.int[2])) [1] -2.539749 17.355816 </code></pre> <p>I am not really finding anything similar in either statsmodels or scipy, which is strange, considering the importance of significance intervals in hypothesis testing (and how much criticism the practice of reporting only the p-values recently got).</p>
<p>Here how to use StatsModels' <a href="http://www.statsmodels.org/stable/generated/statsmodels.stats.weightstats.CompareMeans.html"><code>CompareMeans</code></a> to calculate the confidence interval for the difference between means:</p> <pre><code>import numpy as np, statsmodels.stats.api as sms X1, X2 = np.arange(10,21), np.arange(20,26.5,.5) cm = sms.CompareMeans(sms.DescrStatsW(X1), sms.DescrStatsW(X2)) print cm.tconfint_diff(usevar='unequal') </code></pre> <p>Output is</p> <pre><code>(-10.414599391793885, -5.5854006082061138) </code></pre> <p>and matches R:</p> <pre><code>&gt; X1 &lt;- seq(10,20) &gt; X2 &lt;- seq(20,26,.5) &gt; t.test(X1, X2) Welch Two Sample t-test data: X1 and X2 t = -7.0391, df = 15.58, p-value = 3.247e-06 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -10.414599 -5.585401 sample estimates: mean of x mean of y 15 23 </code></pre>
python|statistics|hypothesis-test
38
1,904,640
38,925,559
Concat/merge xr.DataArray along an existing axis (Xarray | Python 3)
<p>Here is a toy example but I have 2 dataframes; (1) rows=samples, cols=attributes; and (2) rows=samples, cols=metadata-fields.</p> <p>I want to <code>concat</code> or <code>merge</code> to create 3-dimensional <code>xr.DataArray</code>. I've done this multiple times but I can't figure out why it's not working in this case? I want to <code>concat</code> along the <code>patient_id</code> axis to have a 3D <code>xr.DataArray</code>.</p> <p><strong>Why isn't <code>xr.concat</code> building the 3-dimensional <code>DataArray</code>? I think I'm incorrectly using the <code>dim</code> argument since it is supposed to <code>concat</code> along a new-axis but is there a way to do this along an existing axis?</strong> </p> <p>I'm trying to use the method from <a href="https://stackoverflow.com/questions/36948476/create-dataarray-from-dict-of-2d-dataframes-arrays">Create DataArray from Dict of 2D DataFrames/Arrays</a> but it isn't working. I got <code>merge</code> to work but it puts it into a <code>DataSet</code> w/ 2 data variables</p> <pre><code>np.random.seed(0) patient_ids = ["patient_%d"%_ for _ in range(42)] attr_ids = ["attr_%d"%_ for _ in range(481)] meta_ids = ["meta_%d"%_ for _ in range(32)] DA_A = xr.DataArray(pd.DataFrame(np.random.random((42,481)), index=patient_ids, columns=attr_ids), dims=["patient_id","attribute"]) DA_B = xr.DataArray(pd.DataFrame(np.random.random((42,32)), index=patient_ids, columns=meta_ids), dims=["patient_id","metadata"]) DA_A.coords # Coordinates: # * patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ... # * attribute (attribute) object 'attr_0' 'attr_1' 'attr_2' 'attr_3' ... DA_B.coords # Coordinates: # * patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ... # * metadata (metadata) object 'meta_0' 'meta_1' 'meta_2' 'meta_3' ... xr.concat([DA_A, DA_B], dim="patient_id") # KeyError: 'attribute' </code></pre>
<p>You can't (yet) concatenate DataArrays with different dimensions. You need to broadcast them explicitly first, e.g.,</p> <pre><code>In [38]: xr.concat(xr.broadcast(DA_A, DA_B), dim="patient_id") Out[38]: &lt;xarray.DataArray (patient_id: 84, attribute: 481, metadata: 32)&gt; array([[[ 0.5488135 , 0.5488135 , 0.5488135 , ..., 0.5488135 , 0.5488135 , 0.5488135 ], ..., [ 0.79649197, 0.97094708, 0.95542135, ..., 0.37856775, 0.65855316, 0.37893685]]]) Coordinates: * attribute (attribute) object 'attr_0' 'attr_1' 'attr_2' 'attr_3' ... * metadata (metadata) object 'meta_0' 'meta_1' 'meta_2' 'meta_3' ... * patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ... </code></pre> <p>But as jhamman mentions in the comment on your question, you might actually find it easier to work with a single <code>Dataset</code> object instead, with two different variables, e.g.,</p> <pre><code>In [39]: xr.Dataset({'A': DA_A, 'B': DA_B}) Out[39]: &lt;xarray.Dataset&gt; Dimensions: (attribute: 481, metadata: 32, patient_id: 42) Coordinates: * patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ... * attribute (attribute) object 'attr_0' 'attr_1' 'attr_2' 'attr_3' ... * metadata (metadata) object 'meta_0' 'meta_1' 'meta_2' 'meta_3' ... Data variables: A (patient_id, attribute) float64 0.5488 0.7152 0.6028 0.5449 ... B (patient_id, metadata) float64 0.2438 0.8216 0.9237 0.3999 ... </code></pre>
python|pandas|python-xarray
1
1,904,641
40,563,310
Python - Parsing a text onto columns by the position of each item
<p>The Bovespa (brazilian stock exchange) offer a file with all the quotes in a timeframe. The file is too large, and each line are something like this real sample:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>012016010402AAPL34 010APPLE DRN R$ 000000000415000000000042200000000004150000000000421300000000042080000000003950000000000435000005000000000000012500000000000052664400000000000000009999123100000010000000000000BRAAPLBDR004115</code></pre> </div> </div> </p> <p>So, looking for the docs, I found that the column mapping is something like that:</p> <ul> <li>char 01 to 02: (int) type of register;</li> <li>char 03 to 10: (date) date of the stock quote info;</li> <li>char 11 to 12: (int) some kind of code;</li> <li>char 13 to 24: (str) the stock ticker;</li> <li>....</li> </ul> <p>I'm starting to study Python and trying to read a file which contains this data, and got each line sucessfull with this code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import pandas as pd dataset1 = pd.read_table('bmfbovespaquotes/DemoCotacoesHistoricas12022003.txt')</code></pre> </div> </div> </p> <p>I think that maybe this is a silly question, but I didn't find the solution already, so if you know a way to solve this, please share.</p> <p>Thanks</p>
<p>You have a <strong><em>f</strong>ixed <strong>w</strong>idth <strong>f</strong>ormat</em>: this will do the trick.</p> <pre><code>pd.read_fwf(file_path, widths=[...], names=[...]) </code></pre> <p>you should pass the list of widths, which in your case starts as <code>[2,8,2,10,...]</code> and the list of columns <code>['register','date','code','ticker',...]</code></p>
python|pandas|jupyter|bigdata
3
1,904,642
40,732,906
Is it possible to scrape a "dynamical webpage" with beautifulsoup?
<p>I am currently begining to use beautifulsoup to scrape websites, I think I got the basics even though I lack theoretical knowledge about webpages, I will do my best to formulate my question.</p> <p>What I mean with dynamical webpage is the following: a site whose HTML changes based on user action, in my case its collapsible tables.</p> <p>I want to obtain the data inside some "div" tag but when you load the page, the data seems unavalible in the html code, when you click on the table it expands, and the "class" of this "div" changes from something like "something blabla collapsible" to "something blabla collapsible active" and this I can scrape with my knowledge.</p> <p>Can I get this data using beautifulsoup? In case I can't, I thought of using something like selenium to click on all the tables and then download the html, which I could scrape, is there an easier way?</p> <p>Thank you very much.</p>
<p>It depends. If the data is already loaded when the page loads, then the data is available to scrape, it's just in a different element, or being hidden. If the click event triggers loading of the data in some way, then no, you will need Selenium or another headless browser to automate this.</p> <p>Beautiful soup is <strong>only</strong> an HTML parser, so whatever data you get by requesting the page is the only data that beautiful soup can access.</p>
python|html|selenium|beautifulsoup
0
1,904,643
40,685,571
Compare non identical objects with same value
<p>I have 2 lists,both in different formats but same content. For example, doing a simple print command for the 1st elements of the list does the following:</p> <pre><code>prefix_txt[0]=SEF00 prefix_confluence[0]=[u'SEF00'] </code></pre> <p>I get the 'u' here is due to the encoding..</p> <p>The prefix_confluence is being parsed by a HTML parser this way:</p> <pre><code>soup=BeautifulSoup(sample,'html.parser') for row in soup.find_all('tr')[2:171]: prefix_confluence.append(row.get_text(strip=True, separator='|').split('|')[0:1]) </code></pre> <p>Now, how do I compare and show that these 2 list elements are in fact equal in content? I have tried this:</p> <pre><code>new=str(prefix_confluence[0]).strip('[u'']') if(prefix_txt[0]==new): print "They are same." </code></pre> <p>But they dont display the print message due to obvious reasons. How can I make them equal? I also tried join, concatenation but was not able to make it work.</p>
<p>If <code>prefix_txt[0]</code> is a string <code>'SEF00'</code>, and <code>prefix_confluence[0]</code> is a list containing a unicode version of that same string <code>[u'SEF00']</code>, then you should be able to do the following:</p> <pre><code>new = prefix_confluence[0][0] if(prefix_txt[0] == new): print "They are same." </code></pre> <p>When you do <code>new = str(prefix_confluence[0]).strip('[u'']')</code> you will get the string <code>"'SEF00'"</code>, which as you can see is slightly different from the string <code>'SEF00'</code>. Instead, you can get the string out of the list by indexing the list: <code>prefix_confluence[0][0]</code>, which will give you <code>u'SEF00'</code>. Although this looks different from <code>'SEF00'</code>, in Python 2.x they are seen as equal; i.e., <code>'SEF00' == u'SEF00'</code> is <code>True</code>, although their types are different and they do not point to the same object:</p> <pre><code>&gt;&gt;&gt; a = 'foo' &gt;&gt;&gt; b = u'foo' &gt;&gt;&gt; a == b True &gt;&gt;&gt; a is b False &gt;&gt;&gt; type(a) &lt;type 'str'&gt; &gt;&gt;&gt; type(b) &lt;type 'unicode'&gt; </code></pre> <p>And for completeness, the same solution will work in Python 3.x, although what is happening is slightly different. In Python 3, all strings are unicode by default, so not only are <code>'SEF00'</code> and <code>u'SEF00'</code> equal in Python 3, they should generally point to the same object as far as I know:</p> <pre><code>&gt;&gt;&gt; a = 'foo' &gt;&gt;&gt; b = u'foo' &gt;&gt;&gt; a == b True &gt;&gt;&gt; a is b True &gt;&gt;&gt; type(a) &lt;class 'str'&gt; &gt;&gt;&gt; type(b) &lt;class 'str'&gt; </code></pre>
python|list
1
1,904,644
9,982,235
PyWin32 using MakePy utility and win32com to get Network Statistics
<p>This question is in continuation to my <a href="https://stackoverflow.com/q/9970054/776084">previous question</a>.</p> <p>I am trying to get <code>Network Statistics</code> for my <code>Windows 7</code> system using <code>PyWin32</code>.</p> <p>The steps I followed:</p> <blockquote> <p>1) Run <code>COM MakePy utility</code> and than select <code>network list manager 1.0 type library</code> under type library.</p> <p>2) Above process generated this <a href="http://pastebin.com/y7hQGQdR" rel="nofollow noreferrer">python file</a>.</p> </blockquote> <p>Next I created the object of class <code>NetworkListManager(CoClassBaseClass)</code> using </p> <pre><code>import win32com.client as wc obj = wc.Dispatch("{DCB00C01-570F-4A9B-8D69-199FDBA5723B}") </code></pre> <p>Now I am trying to access the methods provided by the above created object <code>obj</code>.</p> <p><code>help(obj)</code> gave me</p> <p><strong>GetNetwork(self, gdNetworkId= <code>&lt;PyOleEmpty object&gt;</code>)</strong></p> <pre><code>Get a network given a Network ID. </code></pre> <p><strong>IsConnected</strong></p> <pre><code>Returns whether connected to internet or not //Other methods removed </code></pre> <p>So, now when I use </p> <pre><code>&gt;&gt;&gt; obj.IsConnected True </code></pre> <p>It works fine.</p> <p>Now the problem I am facing is how to use <code>GetNetowrk</code> method because when I try to use it </p> <pre><code>&gt;&gt;&gt; obj.GetNetwork() Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; ret = self._oleobj_.InvokeTypes(2, LCID, 1, (9, 0), ((36, 1),),gdNetworkId com_error: (-2147024809, 'The parameter is incorrect.', None, None) </code></pre> <p>I also tried creating <code>PyOleEmpty object</code> by using <code>pythoncom.Empty</code> and passed it as a paremeter but no luck.</p> <p>I understand <code>GetNetwork</code> require <code>NetworkID</code> as a parameter but the method <code>GetNetworkId</code> is defined in <a href="http://pastebin.com/qRWWjuD4" rel="nofollow noreferrer">INetwork</a> class.</p> <p>So my question is how to use classes defined in the python file created using <code>MakePy utility</code> which are not <code>CoClass</code>.</p>
<p>It looks like the way to get to the Network objects is to enumerate them using GetNetworks:</p> <pre><code>networks=obj.GetNetworks(win32com.client.constants.NLM_ENUM_NETWORK_CONNECTED) for network in networks: print (network.GetName(), network.GetDescription()) </code></pre> <p>Using the network ids will be problematic. They're defined as raw structs, so they will need to be passed using Records. Pywin32's support for the IRecordInfo interface is still somewhat weak.</p>
python|windows|pywin32
2
1,904,645
68,396,081
I am trying to plot a bar graph, but I am constantly getting this error
<p>My code:</p> <pre><code>Dict = {'b':1 , 'n':1, '-':20, '\xa0':5} x = list(Dict.keys()) y = list(Dict.values()) fig = plt.figure(figsiz = (10,5)) plt.bar(x,y,width = 0.5, color = 'maroon') </code></pre> <p>Error:</p> <pre><code>unsupported operand type(s) for -: 'float' and 'str' </code></pre>
<p>Matplotlib is telling you that it doesn't know how to plot your <code>Dict.keys()</code> on the X axis. You'll need to plot your bars with numeric values for the X axis and then you can assign the <code>Dict.keys()</code> to the bars as tick labels. You'll need to adjust the plot scale and/or your data dictionary to get the data to display properly. The following code shows how to get the data to plot and how to assign the tick labels (but does not make any other adjustments).</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt # Dict = {u'b':1 , u'n':1, u'-':20, u'\xa0':5} x = [1, 2, 3, 4] y = [1, 1, 20, 5] labels = [u'b', u'n', u'-', u'\xa0'] # Note that '\xa0' is a non-breaking space fig = plt.figure(figsize = (10,5)) plt.bar(x,y,width = 0.5, color = 'maroon') plt.xticks(x, labels) plt.show() </code></pre> <p>Note: depending on your Python version, you can't guarantee in what order the dictionary keys and values will be delivered. I've updated this answer to hard-code the data, to make the answer to your original question more obvious.</p>
python|dictionary|matplotlib
0
1,904,646
68,050,836
Memory usage of an array of arrays referencing a single array?
<p>Suppose in Python3 I have an array of size N and an array of N arrays.</p> <pre><code>a = [] b = [] for i in range(N): a.append(i) for i in range(N): b.append(a) </code></pre> <p>Each b[i] now references the same array <strong>a</strong>. I think that this is still O(N) memory because when I access an array I am really accessing a reference to a block of memory so each b[i] holds constant space memory (the address to a) and the array <strong>a</strong> holds O(N) memory, so altogether this should be O(N) memory, rather than O(N^2) if each of the N^2 cells in b holds an independent value. Is this correct?</p>
<p>Yes, this is correct. <code>a</code>'s size is O(n), and <code>b</code> holds N references <strong>to the same instance of <code>a</code></strong>. Overall, the memory complexity is O(n).</p>
python|python-3.x|space-complexity
2
1,904,647
26,263,863
How to get python to pick up OS timezone change?
<p>In a running instance of python, is there a function I can call to say "Hey python, refresh what you know about timezone information"? So lets say I open python, and then I change /etc/localtime . How can I get python to update to the new timezone? My goal is to not mess around with the TZ environment variable or reference /etc/localtime directly or use any OS-specific commands. I would also like to not restart python. Is this possible?</p>
<p>The answer I was looking for was <a href="https://docs.python.org/2/library/time.html#time.tzset" rel="noreferrer">time.tzset()</a>:</p> <pre><code>&gt;&gt;&gt; time.tzname[time.daylight] 'CDT' &gt;&gt;&gt; #Use dpkg-reconfigure tzdata ... &gt;&gt;&gt; time.tzset() &gt;&gt;&gt; time.tzname[time.daylight] 'EDT' &gt;&gt;&gt; </code></pre>
python|timezone
5
1,904,648
60,223,045
Plotting two figures side by side
<p>As title says, I am struggling to plot two plots together, side by side. Conceptually, the code is the following:</p> <pre><code>def my_func(arr): plt.scatter(arr[:, 0], arr[:, 1]) fig, ax = plt.subplots(1, 2, sharex='col', sharey='row') arr1 = np.array([[1, 2], [2, 2], [4, 3], [6, 4], [5, 6]]) for i in range(2): my_func(arr1 + i) </code></pre> <p>The issue here is to plot two plots together using my_func - a function that creates a plot (using multiple parameters, so it is should to be a separate function). The problem here is that two plots that were supposed to be plotted in two different boxes are plotted in the same box. How to fix it?</p>
<p>You need to pass the respective axis objects to your function for plotting</p> <pre><code>def my_func(arr, ax): ax.scatter(arr[:, 0], arr[:, 1]) fig, ax = plt.subplots(1, 2, sharex='col', sharey='row') arr1 = np.array([[1, 2], [2, 2], [4, 3], [6, 4], [5, 6]]) for i in range(2): my_func(arr1 + i, ax[i]) </code></pre> <p><a href="https://i.stack.imgur.com/iLY81.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iLY81.png" alt="enter image description here"></a></p>
python|matplotlib|subplot
2
1,904,649
60,105,595
Why can I not install modules on Python
<p>I'm coding this on IDLE on a MacBook, if that's helpful to anyone.</p> <pre><code>#!/usr/bin/env python3 pip install pynput from pynput import keyboard def get_key_name(key): if isinstance(key, keyboard.KeyCode): return key.char else: return str(key) def on_press(key): key_name = get_key_name(key) print('Key {} pressed.'.format(key_name)) def on_release(key): key_name = get_key_name(key) print('Key {} released.'.format(key_name)) if key_name == 'Key.esc': print('Exiting...') return False with keyboard.Listener( on_press = on_press, on_release = on_release) as listener: listener.join() </code></pre> <p>I am trying to install pynput. But it keeps saying invalid syntax around "install". Can someone help me out please? Thanks!</p>
<p>Try to use <code>pip install pynput</code> from command prompt. You cannot use pip install in your py code file.</p> <p>If you want to install it from code. Try the following:-</p> <pre><code>import subprocess import sys def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package]) install('pynput') </code></pre>
python|module|installation
-1
1,904,650
1,971,911
Replace letters in a secret text
<p>I want to change every letter in a text to after next following letter. But this program doesnt work. Does anyone know why. Thanks in advance. There is also a minor problem with y and z.</p> <pre><code>import string letters = string.ascii_lowercase text=("g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj. ") for x in range(1,24): text.replace(letters[x],letters[x+2]) print(text) </code></pre>
<p>Strings are <strong>immutable</strong> in python.</p> <p>So <code>text.replace</code> <em>returns</em> a string, but doesn't change its original string.</p> <p>Given that, you shouldn't actually use <code>text.replace</code>, since you would have to change the string 24 (or probably 26; see below) times. Rather, you can actually create a translation table to do all the changes at once, and use <code>string.translate</code>.</p> <p>To do that, you should first use <code>string.maketrans</code> to convert from the letters to the second letter following (and what do you want to do with 'y' and 'z'? I expect they should probably become 'a' and 'b'). That will give you a translation table over all possible characters for <code>translate</code>.</p>
python|string
8
1,904,651
32,253,900
How to interactively display and hide lines in a Bokeh plot?
<p>It would be nice to be able to interactively display and hide lines in a bokeh plot. Say, I have created my plot something like this:</p> <pre><code>from bokeh.plotting import output_file, figure, show from numpy.random import normal, uniform meas_data_1 = normal(0, 1, 100) meas_data_2 = uniform(-0.5, 0.5, 100) output_file("myplot.html", title="My plot") fig = figure(width=500, plot_height=500) fig.line(x=range(0, len(meas_data_1)), y=meas_data_1) fig.line(x=range(0, len(meas_data_2)), y=meas_data_2) show(fig) </code></pre> <p>How can I add the possibility to interactively enable/disable one of the two lines?</p> <p>I know that this is on the wish list (see <a href="https://github.com/bokeh/bokeh/issues/2274" rel="noreferrer">this feature request</a>), but that doesn't sound like it would be implemented too soon. </p> <p>I have the impression that this should be possible using a <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction.html#checkbox-group" rel="noreferrer">CheckBoxGroup</a> and a <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction.html#callbacks-for-widgets" rel="noreferrer">self-defined callback</a>, but unfortunately this callback has to be written in JavaScript, which I have absolutely no experience in.</p>
<p><strong>EDIT</strong>: Interactive legends are now built into the library as of Bokeh <code>0.12.5</code>, see <a href="https://bokeh.github.io/blog/2017/4/5/release-0-12-5/" rel="noreferrer">https://bokeh.github.io/blog/2017/4/5/release-0-12-5/</a></p> <hr> <p>This appears on track to be implemented at some point as interactive legends: <a href="https://github.com/bokeh/bokeh/issues/3715" rel="noreferrer">https://github.com/bokeh/bokeh/issues/3715</a></p> <p>Currently (v0.12.1), there is an example that uses CustomJS on checkboxes to achieve this: <a href="https://github.com/bokeh/bokeh/pull/4868" rel="noreferrer">https://github.com/bokeh/bokeh/pull/4868</a></p> <p>Relevant code:</p> <pre><code>import numpy as np from bokeh.io import output_file, show from bokeh.layouts import row from bokeh.palettes import Viridis3 from bokeh.plotting import figure from bokeh.models import CheckboxGroup, CustomJS output_file("line_on_off.html", title="line_on_off.py example") p = figure() props = dict(line_width=4, line_alpha=0.7) x = np.linspace(0, 4 * np.pi, 100) l0 = p.line(x, np.sin(x), color=Viridis3[0], legend="Line 0", **props) l1 = p.line(x, 4 * np.cos(x), color=Viridis3[1], legend="Line 1", **props) l2 = p.line(x, np.tan(x), color=Viridis3[2], legend="Line 2", **props) checkbox = CheckboxGroup(labels=["Line 0", "Line 1", "Line 2"], active=[0, 1, 2], width=100) checkbox.callback = CustomJS(args=dict(l0=l0, l1=l1, l2=l2, checkbox=checkbox), lang="coffeescript", code=""" l0.visible = 0 in checkbox.active; l1.visible = 1 in checkbox.active; l2.visible = 2 in checkbox.active; """) layout = row(checkbox, p) show(layout) </code></pre>
javascript|python|bokeh
14
1,904,652
43,959,585
PyTables ptrepack cmd not accepting absolute path
<p><strong>Relative path:</strong> </p> <pre><code>C:\Users&gt;ptrepack JRC\git\metaTest.h5 JRC\git\cmdTest.h5 </code></pre> <p>Produces the correct results</p> <p><strong>Absolute path:</strong> </p> <pre><code>C:\Users&gt;ptrepack C:\Users\JRC\git\metaTest.h5 C:\Users\JRC\git\xxcmdTest.h5 </code></pre> <p>Gives the Following error</p> <pre><code>Traceback (most recent call last): File "C:\Users\JRC\Anaconda3\Scripts\ptrepack-script.py", line 5, in &lt;module&gt; sys.exit(tables.scripts.ptrepack.main()) File "C:\Users\JRC\Anaconda3\lib\site-packages\tables\scripts\ptrepack.py", line 508, in main h5srcfile = open_file(srcfile, 'r') File "C:\Users\JRC\Anaconda3\lib\site-packages\tables\file.py", line 318, in open_file return File(filename, mode, title, root_uep, filters, **kwargs) File "C:\Users\JRC\Anaconda3\lib\site-packages\tables\file.py", line 784, in _ _init__ self._g_new(filename, mode, **params) File "tables\hdf5extension.pyx", line 370, in tables.hdf5extension.File._g_new (tables\hdf5extension.c:4321) File "C:\Users\JRC\Anaconda3\lib\site-packages\tables\utils.py", line 157, in check_file_access raise IOError("``%s`` does not exist" % (filename,)) IOError: ``C`` does not exist </code></pre> <p>Am I doing something wrong, it doesn't seem to be interpreting the C as a drive letter.</p>
<p>There is an issue on github <a href="https://github.com/PyTables/PyTables/issues/616" rel="nofollow noreferrer">https://github.com/PyTables/PyTables/issues/616</a> I also met this problem, i used workaround - to add ":" to end of path, for example: C:\Users>ptrepack C:\Users\JRC\git\metaTest.h5: C:\Users\JRC\git\xxcmdTest.h5:</p>
python|cmd|hdf5|pytables
1
1,904,653
32,636,307
How to save DateField in django
<p>I got this error, but I'm not sure why.</p> <blockquote> <p>TypeError: 'Daily' object does not support item assignment</p> </blockquote> <p>here is the code:</p> <pre><code>yesterday = datetime.datetime.utcnow() - timedelta(days=1) item['date'] = yesterday </code></pre> <p><strong>models.py</strong></p> <pre><code>date = models.DateField(blank=True, null=True) </code></pre> <p>I changed </p> <pre><code>date = models.DateField(auto_now_add=True, blank=True, null=True) </code></pre> <p>to </p> <pre><code>date = models.DateField(blank=True, null=True) </code></pre> <p>How to save DateField in django?.</p>
<pre><code>item.date = yesterday </code></pre> <p>As the error says, Django models do not support item assignments (the [] syntax), but attributes, with the <code>.</code>.</p>
python|django
2
1,904,654
32,605,227
Serial communication sending/receiving data between Arduino and Python
<p>I've connected both Arduino and Raspberry Pi vis USB serial communication. On Raspeberry Side, Python code has to read three ultrasonic sensors using below attached code. Thus, depending to sensors information Python will send command via a string e.g. M, 2000, 1500 to drive the two wheels of a robot. The problem is each time I run python code, it loses some digits or comma, for example if Arduino sends 200, 122, 60 (left, centre, right) distance, on python side I receive some times same data but most the time there is a missing number or even the comma and thus the split function shows error because instead of having three sensors if I lose the comma in reading then it will be just like two sensors.</p> <pre><code>import serial import time import string DEVICE = '/dev/ttyACM0' BAUD = 9600 ser= serial.Serial(DEVICE, BAUD) while (1==1): Sensors_Data=ser.readline() print Sensors_Data (left_distance, centre_distance, right_distance)=[int(s) for s in Sensors_Data.split(',')] print left_distance print centre_distance print right_distance if (centre_distance&lt;50): ser.write('M%4d' %1500) ser.write('M%4d' %1500) else: ser.write('M%4d' %1600) ser.write('M%4d' %1500) </code></pre>
<p>First let's make sure you don't have extraneous characters like newlines and carriage returns.</p> <pre><code>import serial import time import string DEVICE = '/dev/ttyACM0' BAUD = 9600 ser= serial.Serial(DEVICE, BAUD) while (1==1): Sensors_Data=ser.readline().encode('string-escape') print Sensors_Data # This should show you what all is there. Sensors_Data = Sensors_Data.split('\r\n')[0] # Assuming you have a carriage return and a newline, which is typical. (left_distance, centre_distance, right_distance)=[int(s) for s in Sensors_Data.split(',')] print left_distance print centre_distance print right_distance if (centre_distance&lt;50): ser.write('M%4d' %1500) ser.write('M%4d' %1500) else: ser.write('M%4d' %1600) ser.write('M%4d' %1500) </code></pre>
python|arduino-uno|raspberry-pi2
1
1,904,655
27,175,867
Google Admin SDK error Resource Not Found: domain when trying to list existing users
<p>I am trying to write a simple script to get a list of my Google Apps users using Google's python API. So far it looks like this (based on a Google example):</p> <pre><code>!/usr/bin/python import httplib2 from apiclient import errors from apiclient.discovery import build from oauth2client.client import OAuth2WebServerFlow from oauth2client.client import SignedJwtAssertionCredentials client_email = 'service_account_email@developer.gserviceaccount.com' with open("Python GAPS-98dfb88b4c9f.p12") as f: private_key = f.read() OAUTH_SCOPE = 'https://www.googleapis.com/auth/admin.directory.user' credentials = SignedJwtAssertionCredentials(client_email, private_key, OAUTH_SCOPE ) http = httplib2.Http() http = credentials.authorize(http) directory_service = build('admin', 'directory_v1', http=http) all_users = [] page_token = None params = {'customer': 'my_customer'} while True: try: if page_token: param['pageToken'] = page_token current_page = directory_service.users().list(**params).execute() all_users.extend(current_page['users']) page_token = current_page.get('nextPageToken') if not page_token: break except errors.HttpError as error: print 'An error occurred: %s' % error break for user in all_users: print user['primaryEmail'] </code></pre> <p>The service account has been authorized on google developer console for the following API's:</p> <p><a href="https://www.googleapis.com/auth/admin.directory.user" rel="nofollow">https://www.googleapis.com/auth/admin.directory.user</a> <a href="https://www.googleapis.com/auth/admin.directory.user.alias" rel="nofollow">https://www.googleapis.com/auth/admin.directory.user.alias</a> </p> <p>However, when I run the code, I get this error:</p> <pre><code>An error occurred: &lt;HttpError 404 when requesting https://www.googleapis.com/admin/directory/v1/users?customer=my_customer&amp;alt=json returned "Resource Not Found: domain"&gt; </code></pre> <p>Any hints on what am I missing?</p> <p>E.</p>
<p>Even when using a service account, you still need to "act as" a Google Apps user in the domain with the proper rights (e.g. a super admin). Try:</p> <pre><code>credentials = SignedJwtAssertionCredentials(client_email, private_key, OAUTH_SCOPE, sub='admin@domain.com') </code></pre> <p>where admin@domain.com is the email of a super admin in your domain.</p>
python|google-apps|google-directory-api
3
1,904,656
12,297,500
python module for nslookup
<p>Is there a python-module that's doing the same stuff as nslookup does? I am planning to use nslookup on digging some information regarding the domain of a URL to be scrapped. I know I can use os.sys to call nslookup but I am just wondering if there is a python-module for this already. Thanks in advance!</p>
<p>I'm using the following code:</p> <pre><code>import socket ip_list = [] ais = socket.getaddrinfo("www.yahoo.com",0,0,0,0) for result in ais: ip_list.append(result[-1][0]) ip_list = list(set(ip_list)) </code></pre> <p>Or using a comprehension as:</p> <pre><code>ip_list = list({addr[-1][0] for addr in socket.getaddrinfo(name, 0, 0, 0, 0)}) </code></pre>
python-module|nslookup
50
1,904,657
23,330,835
Python tkinter: replace inputs with key presses?
<p>I am new to programming and python and have been writing a simple text-based RPG using the console for output and input. I want to change to using tkinter for text output into widgets and key input via keyboard presses. After getting the tkinter window layout how I want it I just can't figure out how to get the different inputs to use tkinter events.</p> <pre><code>def main_menu(hero): choice = ' ' while choice not in ['0', '1', '2', '3']: while choice != '0' and hero.health &gt; 0: print("\n" * 80) print(hero) print("Where would you like to go?\n" "[1] Adventure\n" "[2] Temple\n" "[3] Store\n\n" "[0] Save &amp; Quit") choice = input("&gt;") if choice == '1': adventure(hero) elif choice == '2': temple(hero) elif choice == '3': store(hero) elif choice == '0': save(hero) </code></pre> <p>And when an input for <em>choice</em> through tkinter has been made I want it to continue down into the next function for example <em>store()</em> where I want to get a new input from tkinter to resolve which function to call next</p> <pre><code>def store(hero): item_type = '' while item_type not in ['1', '2', '3']: print("\n" * 80) print("What would you like to buy?" "\n[1] Weapons" "\n[2] Armor" "\n\n[3] Leave") item_type = str(input("&gt;")) if item_type == '1': weapon_store(hero) item_type = '' elif item_type == '2': armor_store(hero) item_type = '' else: input("Okay, have a good day.\n") </code></pre>
<p>I managed to solve my problem by changing the key-pressed as a StringVar and then using wait_variable in the code where I want it to receive a new input.</p>
python-3.x|tkinter
0
1,904,658
683,278
Can pysvn 1.6.3 be made to work with Subversion 1.6 under linux?
<p>I see no reference on their website for this. I get pysvn to configure and build, but then it fails all the test. Has anyone had any luck getting this to work under linux?</p>
<p>No, it cannot. </p> <p>Your best bet is to use Subversion 1.5.5. See <a href="http://pysvn.tigris.org/project_status.html" rel="nofollow noreferrer">the site</a> for more details. </p>
python|linux|svn|pysvn
1
1,904,659
47,141,059
How to randomly select 10 items from csv dictionary?
<p>In my .csv file I have 12 countries in total (with 12 capitals) I want to randomly select 10 of those 12 countries however.</p> <p>I've found from stackoverflow resources some single or pair selection but not randomly select 10 items from a dictionary. How can I do this?</p> <p>This is the relevant code I have for a countries and capitals exam where user inputs the capital to the country asked, and outputs a correct or incorrect answer.</p> <pre><code> #Defining the function of reading .csv file from path into dictionary def readCsvIntoDictionary(path): dic = {} with open(path, 'r', newline='') as f: reader = csv.reader(f) for row in reader: dic[row[0]] = row[1]; return dic; count = 0; # for loop with key variable definition in dic for key in dic: # ans variable defined for user input ans = input('What is the capital of ' + key + '?\n') # User can input lower and upper answers if(ans.lower() == dic[key].lower()): # key lookup in dic (dictionary) if answer is correct at end of the loop dic[key] = 'Correct! ' + dic[key] + ' is the capital of ' + key; count = count + 1; else: # key lookup in dic (dictionary) if answer is incorrect at end of the loop dic[key] = 'Wrong! \'' + ans + '\' is not the capital of ' + key + ', it\'s ' + dic[key]; </code></pre> <p>Thanks!</p>
<p>You're looking to <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow noreferrer"><code>sample</code></a> the keys:</p> <pre><code>for key in random.sample(dic.keys(), 10): </code></pre>
python-3.x|csv|dictionary|case
1
1,904,660
47,091,732
How do I initialize a column vector of a 2D list/array in python?
<p>Suppose I have a list of list called <code>mat</code> of shape <code>5x5</code>. </p> <p>Then I initialize a "column", element by element as follows</p> <pre><code>mat[0][4] = 'X' mat[1][4] = 'O' mat[2][4] = 'R' mat[3][4] = 'N' mat[4][4] = 'A' </code></pre> <p>Is there any way to initialize this column vector in one line in <code>Python</code> like how <code>MATLAB</code> might do?</p> <pre><code>mat[:,4] = ['X','O','R','N','A'] </code></pre>
<p>Not quite as concise, but:</p> <pre><code>for i,x in enumerate(['X','O','R','N','A']): mat[i][4]=x </code></pre> <p>Or in the case of single characters, slightly shorter:</p> <pre><code>for i,x in enumerate('XORNA'): mat[i][4]=x </code></pre> <hr> <p>Alternatively, you can use <code>numpy</code>:</p> <pre><code>import numpy mat=numpy.array([[' ' for i in range(5)] for j in range(5)]) mat[:,4] = ['X','O','R','N','A'] </code></pre>
python|arrays|python-2.7|python-3.x|matrix
1
1,904,661
47,517,047
How should I unit test my Pyramid app's route matching?
<p>I am writing a Pyramid web application that uses URL dispatch for mapping routes to views.</p> <p>I would like to write a set of unit tests that provide Pyramid's "route matcher" with a variety of paths, and then assert that:</p> <ol> <li>the correct view is called</li> <li>the <code>request.matchdict</code> contains the expected contents</li> </ol> <p>How can I do this at a proper <em>unit</em> test level (as opposed to at a functional level, by submitting actual HTTP requests)? Which "unit" in Pyramid actually does the route matching, and how can I access it to test my app's configured routing?</p> <p><strong>NOTE</strong>: I know I can do this using <em>functional</em> testing, but I am asking this question because I want to know how to test it much more narrowly--just the route matching portion. I suppose what I'm looking for might be considered an integration test and not a unit test, because it touches multiple components...</p> <p>I have Googled and read relevant Pyramid documentation, including <a href="https://docs.pylonsproject.org/projects/pyramid/en/latest/quick_tutorial/routing.html" rel="nofollow noreferrer" title="Dispatching URLs To Views With Routing">Dispatching URLs To Views With Routing</a> and <a href="https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/testing.html" rel="nofollow noreferrer">Unit, Integration, and Functional Testing</a>. Nothing I have seen shows me how to test my application's configured routes without doing functional tests.</p>
<p>There is not a public api to do this in Pyramid. However, there is a private and pretty stable API for it.. you've been warned.</p> <p>Route matching doesn't occur on just patterns but also predicates so it requires a full request object to do matching, not just a url.</p> <pre><code>registry = config.registry or request.registry mapper = registry.getUtility(pyramid.interfaces.IRoutesMapper) result = mapper(request) route, matchdict = result['route'], result['match'] if route is not None: route # pyramid.interfaces.IRoute object matchdict # request.matchdict </code></pre> <p>The raw <code>IRoute</code> objects themselves <strong>are</strong> available on a public api via the introspector. You can look these up and match against them on a per-route basis, but this will ignore the route ordering inherent to Pyramid.</p> <pre><code>introspector = config.registry or request.registry.introspector intr = introspector.get('routes', route_name) route = intr['route'] match = route.match(path) if match is not None: route # pyramid.interfaces.IRoute object match # request.matchdict </code></pre> <p>The route also has the predicates on it which you can pass the <code>request</code> to in order to determine if the predicates pass.</p>
python|unit-testing|pyramid
1
1,904,662
11,970,186
Matplotlib : quiver and imshow superimposed, how can I set two colorbars?
<p>I have a figure that consists of an image displayed by <code>imshow()</code>, a contour and a vector field set by <code>quiver()</code>. I have colored the vector field based on another scalar quantity. On the right of my figure, I have made a <code>colorbar()</code>. This <code>colorbar()</code> represents the values displayed by <code>imshow()</code> (which can be positive and negative in my case). I'd like to know how I could setup another colorbar which would be based on the values of the scalar quantity upon which the color of the vectors is based. Does anyone know how to do that?</p> <p>Here is an example of the image I've been able to make. Notice that the colors of the vectors go from blue to red. According to the current colorbar, blue means negative. However I know that the quantity represented by the color of the vector is always positive.</p> <p><img src="https://i.stack.imgur.com/j5Erm.png" alt="enter image description here"></p>
<p>Simply call <code>colorbar</code> twice, right after each plotting call. Pylab will create a new colorbar matching to the latest plot. Note that, as in your example, the quiver values range from 0,1 while the imshow takes negative values. For clarity (not shown in this example), I would use different colormaps to distinguish the two types of plots. </p> <pre><code>import numpy as np import pylab as plt # Create some sample data dx = np.linspace(0,1,20) X,Y = np.meshgrid(dx,dx) Z = X**2 - Y Z2 = X plt.imshow(Z) plt.colorbar() plt.quiver(X,Y,Z2,width=.01,linewidth=1) plt.colorbar() plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/3fV8I.png" alt="enter image description here"></p>
python|matplotlib|visualization|data-visualization|colorbar
7
1,904,663
11,495,357
gevent monkey-patching and breakpoints
<p>I have been playing with Gevent, and I like it a lot. However I have run into a problem. Breakpoint are not being hit, and debugging doesn't work (using both Visual Studio Python Tools and Eclipse PyDev). This happens after <code>monkey.patch_all()</code> is called.</p> <p>This is a big problem for me, and unfortunately this is a blocker for the use of gevent. I have found a <a href="https://groups.google.com/forum/?fromgroups#!topic/gevent/iBFgoSvyoik">few threads</a> that seem to indicate that gevent breaks debugging, but I would imagine there is a solution for that.</p> <p>Does anyone know how to make debugging and breakpoints work with gevent and monkey patching?</p>
<p>PyCharm IDE solves the problem. It supports gevent code debugging after you set a configuration flag: <a href="http://blog.jetbrains.com/pycharm/2012/08/gevent-debug-support/" rel="noreferrer">http://blog.jetbrains.com/pycharm/2012/08/gevent-debug-support/</a>.</p> <p>Unfortunately, at the moment I don't know a free tool capable of debugging gevent.</p> <p>UPD: THERE IS! Now there is a community version of PyCharm.</p>
python|debugging|pydev|monkeypatching|gevent
9
1,904,664
33,908,356
AttributeError: python: undefined symbol: when accessing C++ function from Python using ctypes
<p>What I am trying to do is call a C++ method from Python to return a 2D array. The Python filename is: BaxterArm1.py and the C++ filename is: baxIK.cpp. Below is how I compiled my c++ program:</p> <pre><code>g++ -c -fPIC baxIK.cpp -o baxIK.o g++ -shared -Wl,-soname,baxIK.so -o baxIK.so baxIK.o </code></pre> <p>Below is the relevant part of the C++ program:</p> <pre><code>int main(int argc, char** argv) { } extern "C" float** compute(float x, float y, float z, float q1, float q2, float q3, float q4) { unsigned int num_of_solutions = (int)solutions.GetNumSolutions(); std::vector&lt;IKREAL_TYPE&gt; solvalues(num_of_joints); float** sols; sols = new float*[(int)num_of_solutions]; for(std::size_t i = 0; i &lt; num_of_solutions; ++i) { sols[i] = new float[7]; for( std::size_t j = 0; j &lt; solvalues.size(); ++j) { printf("%.15f, ", solvalues[j]); sols[i][j] = solvalues[j]; } printf("\n"); } return sols; } </code></pre> <p>The idea is to return a Nx7 array for Python to receive. The Python code is as follows:</p> <pre><code>def sendArm(xGoal, yGoal, zGoal, right, lj): print "Goals %f %f %f" % (xGoal, yGoal, zGoal) output = ctypes.CDLL(os.path.dirname('baxIK.so')) output.compute.restype = POINTER(c_float) output.compute.argtypes = [c_float, c_float, c_float, c_float, c_float, c_float, c_float] res = output.compute(xGoal, yGoal, zGoal, 0.707, 0, 0.7, 0) print(res) </code></pre> <p>The error I get is on the line</p> <pre><code>output.compute.restype = POINTER(c_float) </code></pre> <p>and the traceback is below:</p> <pre><code>File "/home/eadom/ros_ws/src/baxter_examples/scripts/BaxterArm1.py", line 60, in sendArm output.compute.restype = POINTER(c_float) File "/usr/lib/python2.7/ctypes/__init__.py", line 378, in __getattr__ func = self.__getitem__(name) File "/usr/lib/python2.7/ctypes/__init__.py", line 383, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: python: undefined symbol: compute </code></pre> <p>I'm confused as to how I'd fix this. Also, could somebody do a check on this and see if I'm sending the 2D array properly? As it is it's only sending a 1D array but I couldn't find anything on sending a 2D array. I'm grateful for any help.</p>
<p>Finally got it working! Problem is that <code>(os.path.dirname('baxIK.so')</code>was returning an empty string, so I put in the full directory. I fixed the other issue I mentioned earlier by compiling g++ with llapack and now I'm fixing up one last detail. I hope this helps somebody else.</p>
python|c++|numpy|multidimensional-array|ctypes
0
1,904,665
46,637,130
matplotlib smooth animation superimposed on scatter plot
<p>The following Python code in Jupyter shows an example that displays some generated scatter plot data, and it superimposes a line that you can interactively change the y intercept and slope, It also displays the root mean square error. My question is this: How can I make it more responsive? there is a lag and an accumulation of changes that get processed, and it flickers a lot. Can it be faster and more responsive and smoother?</p> <p>///</p> <pre><code>%matplotlib inline from ipywidgets import interactive import matplotlib.pyplot as plt import numpy as np # Desired mean values of generated sample. N = 50 # Desired mean values of generated sample. mean = np.array([0, 0]) # Desired covariance matrix of generated sample. cov = np.array([ [ 10, 8], [ 8, 10] ]) # Generate random data. data = np.random.multivariate_normal(mean, cov, size=N) xdata = data[:, 0] ydata = data[:, 1] # Plot linear regression line def f(m, b): plt.figure() x = np.linspace(-10, 10, num=100) plt.plot(xdata, ydata, 'ro') plt.plot(x, m * x + b) plt.ylim(-10, 10) rmes = np.sqrt(np.mean(((xdata*m+b)-ydata)**2)) print("Root Mean Square Error: ", rmes) interactive_plot = interactive(f, m=(-10.0, 10.0), b=(-10, 10, 0.5)) output = interactive_plot.children[-1] output.layout.height = '350px' interactive_plot </code></pre> <p>///</p> <p><a href="https://i.stack.imgur.com/SehJ4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SehJ4.png" alt="enter image description here"></a></p>
<p>You need to have <code>plt.show()</code> at the end of your function. There was a <a href="https://github.com/ipython/ipython/issues/10376" rel="nofollow noreferrer">github issue about it</a></p> <p>Try using a <code>FloatSlider</code> with <code>continuous_update=False</code>. <a href="http://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html#continuous_update" rel="nofollow noreferrer">See here</a></p> <pre><code>interactive_plot = interactive(f, m=FloatSlider(min=-10.0, max=10.0, continuous_update=False), b=FloatSlider(min=-10, max=10, step=.5, continuous_update=False)) </code></pre>
python|animation|matplotlib|plot|interactive
0
1,904,666
37,775,603
Overwrite valueChanged pyqt5 adding Qt.QueuedConnection
<p>I want to create my own class of QSpinBox and overwriting the valueChanged method to behaviour as I need adding the <code>Qt.QueuedConnection</code> type instead of <code>Qt.AutoConnection</code></p> <p>here is the code I use :</p> <pre><code>class AbstractSpinBox(QtWidgets.QSpinBox): def __init__(self, parent=None): super(AbstractSpinBox, self).__init__(parent) def valueChanged(self, *args, **kwargs): super(AbstractSpinBox, self).valueChanged(*args, **kwargs) </code></pre> <p>How can I achieve that ? Thank you very much.</p>
<p>Why do you need to extend <code>QSpinBox</code> for that? It's a signal, and you'll select the connection type when <em>connecting</em> it, not when defining it.</p>
python|pyqt5
1
1,904,667
37,998,077
Parse non-homogeneous CSV file with Python
<p>I have a CSV file structured like this:</p> <pre><code># Samples 1 1,58 2,995 3,585 # Samples 2 15,87 16,952 17,256 # Samples 1 4,89 5,63 6,27 </code></pre> <p>Is there any way in Python 3.x, how to parse a file structured like this without having to manually go through it line-by-line?</p> <p>I'd like to have some function, which will automatically parse it considering the labels, like this:</p> <pre><code>&gt;&gt; parseLabeledCSV(['# Samples 1', '# Samples 2'], fileName) [{1:58,2:995,3:585,4:89,5:63,6:27}, {15:57, 16:952, 17:256}] </code></pre>
<p>Something like this?</p> <pre><code>input="""# Samples 1 1,58 2,995 3,585 # Samples 2 15,87 16,952 17,256 # Samples 1 4,89 5,63 6,27""" def parse(input): parsed = {} lines = input.split("\n") key = "# Unknown" for line in lines: if line is None or line == "": # ignore empty line continue if line.startswith("#") : if not parsed.has_key(line): parsed[line] = {} key = line continue left, right = line.split(",") parsed[key][left] = right return parsed if __name__ == '__main__': output = parse(input) print(output) </code></pre> <p>will output to:</p> <pre><code>{'# Samples 1': {'1': '58', '3': '585', '2': '995', '5': '63', '4': '89', '6': '27'}, '# Samples 2': {'15': '87', '17': '256', '16': '952'}} </code></pre>
python|python-3.x|csv|parsing
1
1,904,668
27,573,944
Python: How do i run a function simultaneously as other code and update the other Code real time?
<p>I've recently started coding with pygame to create a GUI Radar for a Project which requires real time radar. The problem i've came across is that i want to run the Ultra() function at the same time as the rest of the code allowing me to have real time updates of the "Distance" variable. And i want this Distance variable to update a label on the screen. Any help at all would be greatly appreciated . Thanks!</p> <pre><code>import pygame import time import sys import RPi.GPIO as GPIO import os BLACK = (0,0,0) WHITE = (255,255,255) RED = (255,0,0) GREEN = (0,155,0) BLUE = (0,0,255) pygame.init() clock = pygame.time.Clock() menuW = 400 menuH = 250 mainDisplay = pygame.display.set_mode((menuW, menuH)) pygame.display.set_caption("Radar ALPHA 1.0") #FONTS fontSmall = pygame.font.SysFont(None, 25) fontBig = pygame.font.SysFont(None , 50) #HOMEMADE FUNCTIONS def ultra(): global Distance GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) TRIG = 7 ECHO = 11 GPIO.setup(TRIG,GPIO.OUT) GPIO.output(TRIG,0) GPIO.setup(ECHO,GPIO.IN) time.sleep(1) print "Starting mesurement..." GPIO.output(TRIG,1) time.sleep(0.00001) GPIO.output(TRIG,0) while GPIO.input(ECHO) == 0: pass start = time.time() while GPIO.input(ECHO) == 1: pass stop = time.time() Distance = (stop-start) * 17000 print Distance , " CM" def message_small(msg,colour,width,height): screen_text = fontSmall.render(msg, True, colour) mainDisplay.blit(screen_text, [width, height]) def message_big(msg,colour,width,height): screen_text = fontBig.render(msg, True, colour) mainDisplay.blit(screen_text, [width, height]) def circle(display,r): pygame.draw.circle(display, WHITE, [500, 360], r, 3) def button(bPosX,bPosY,bX,bY): pygame.draw.rect(mainDisplay, GREEN, [bPosX, bPosY, bX, bY] ) menuOn = True guiOn = True radarOn = True dataOn = True infoOn = True #VARs radarSetup = True ultraSetup = True targetSpeed = 5 targetX = 200 targetY = 100 changeTX = 0 changeTY = 0 #MAIN BIT while guiOn: while menuOn: #VARs and SETUP mainDisplay.fill(WHITE) message_big("Radar Menu ALPHA 1.0", RED, 5,5) message_small("Press R to go to Radar", BLACK, 5,50) message_small("Press D to go to Data", BLACK , 5, 70) message_small("Press I to go to Info" , BLACK, 5, 90) message_small("Press Q to Quit" , BLACK, 250,220) pygame.display.update() #EVENT HANDLER for event in pygame.event.get(): if event.type == pygame.QUIT: menuOn = False radarOn = False dataOn = False infoOn = False guiOn = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: menuOn = False dataOn = False infoOn = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_d: menuOn = False radarOn = False infoOn = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_i: menuOn = False radarOn = False dataOn = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: radarOn = False dataOn = False infoOn = False guiOn = False menuOn = False #LOGICS while radarOn: while radarSetup: pygame.init() clock = pygame.time.Clock() menuW = 1000 menuH = 720 radarDisplay = pygame.display.set_mode((menuW, menuH)) pygame.display.set_caption("Radar ALPHA 1.0") radarSetup = False #CLEAR and setup radarDisplay.fill(WHITE) message_big("RADAR v1.0",RED, 400 , 20) #EVENT HANDLER for event in pygame.event.get(): if event.type == pygame.QUIT: menuOn = False radarOn = False dataOn = False infoOn = False guiOn = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: changeTX = - targetSpeed if event.key == pygame.K_RIGHT: changeTX = targetSpeed if event.key == pygame.K_UP: changeTY = - targetSpeed if event.key == pygame.K_DOWN: changeTY = targetSpeed if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: changeTX = 0 if event.key == pygame.K_RIGHT: changeTX = 0 if event.key == pygame.K_UP: changeTY = 0 if event.key == pygame.K_DOWN: changeTY = 0 #Circle Set UP pygame.draw.circle(radarDisplay, BLACK, [menuW/2, menuH/2], 300) pygame.draw.circle(radarDisplay, GREEN, [menuW/2, menuH/2], 20) circle(radarDisplay,50) circle(radarDisplay,100) circle(radarDisplay,150) circle(radarDisplay,200) circle(radarDisplay,250) #LOGICS targetX += changeTX targetY += changeTY pygame.draw.circle(radarDisplay, RED, [targetX, targetY], 5) pygame.display.update() clock.tick(2) while dataOn: #CLEAR mainDisplay.fill(WHITE) message_small("DATA",RED, 150 , 100) pygame.display.update() #VARs #EVENT HANDLER for event in pygame.event.get(): if event.type == pygame.QUIT: menuOn = False radarOn = False dataOn = False infoOn = False guiOn = False #LOGICS while infoOn: #CLEAR mainDisplay.fill(WHITE) message_small("INFO",RED, 150 , 100) pygame.display.update() #VARs #EVENT HANDLER for event in pygame.event.get(): if event.type == pygame.QUIT: menuOn = False radarOn = False dataOn = False infoOn = False guiOn = False #LOGICS clock.tick(10) pygame.quit() quit() </code></pre>
<p>Threads run separately from your code. If you are sharing data between threads make sure they are thread safe object that contain the data otherwise you get read after write errors or other errors from when the data has been change. <a href="https://docs.python.org/3.4/library/threading.html" rel="nofollow">https://docs.python.org/3.4/library/threading.html</a></p> <p>The other way is using the multiprocessing library which is for some major processing.</p> <pre><code>import threading import queue import time def mymethod(storage, stop): """Continuously add counters to the given storage queue. Args: storage (queue.Queue): Hold the data. stop (threading.Event): Thread safe signal for when to quit. """ counter = 0 while not stop.is_set(): storage.put(counter) counter += 1 time.sleep(0.1) # end mymethod if __name__ == "__main__": storage = queue.Queue() stop = threading.Event() th = threading.Thread(target=mymethod, args=(storage, stop)) # th.daemon = True # Daemon threads are cleaned up automatically th.start() # Run for i in range(10): # We don't actually know how fast each program runs. Order will not be saved. print(storage.get(0)) # Pull the thread counter number. 0 means no wait storage.put(i) # Set my counter number time.sleep(0.2) # Just to show things aren't happening in any order. time.sleep(1) # Do other stuff and forget about it. stop.set() # Clear the stop signal, so the thread can leave the loop and quit th.join(0) # Safely close the thread when it is done print("thread closed") while not storage.empty(): print(storage.get(0)) </code></pre>
python|pygame
0
1,904,669
48,740,005
Python: Depth-First-Search (DFS) output post-order number
<p>I want to find out which tuple-node with the same tuple elements (e.g. (1,1), (2,2) or (i, i)) is the source in a particular graph, i.e. which node has the highest post-order number. I want to find the source by applying DFS to it and take the number with the highest post-order number as my source node for further usage. Assume, you have the following graph:</p> <pre><code>graph={ (1,1): [(1,2),(2,2)], (1,2): [(1,3)], (1,3): [(1,2),(2,3)], (2,2): [(3,3)], (2,3): [], (3,3): [(2,2)], } </code></pre> <p>Now I have this iterative dfs function (I have to do it iteratively because I have a massive stack). I was not sure how to extend it to return the node with the highest post-order number.</p> <pre><code>def dfs_iterative_starting(graph, n): # n is the number different numbers (e.g. (1,1), (2,2) or (i,i)) # array in which I'll save the post-order numbers. The index indicates the node, e.g. index 1 -&gt; (1,1) arr = [0]*(n+1) # starting node is (1,1) stack, path = [(1,1)], [] # counter for the post-order number counter = 1 while stack: vertex = stack.pop() if vertex in path: continue path.append(vertex) # counting post-order number???? i, j = vertex if i == j: arr[i] = counter for neighbor in graph[vertex]: stack.append(neighbor) # counting post-order number???? k, j = neighbor counter += 1 if k == j: arr[k] = counter print(arr) return arr.index(max(arr)) </code></pre> <p>For the above-mentioned example, it returns 2 even though the correct answer would be 1. If I print arr, I get the following list [0, 1, 5, 4]</p>
<p>In the recursive implementation, we'd have a subsequent operation to add to the post-order list the node whose neighbours we first explore. This has to be pushed to the stack first. It might help to distinguish what to do with the stack element. Here's one example:</p> <p>JavaScript code (sorry, on smartphone and have no access to Python):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function f(graph){ let stack = [['(1,1)', 'explore']]; let path = new Set(); let post_order = []; while (stack.length){ let [vertex, action] = stack.pop(); if (action == 'mark'){ post_order.push(vertex); continue; } path.add(vertex); stack.push([vertex, 'mark']); for (let neighbour of graph[vertex]){ if (!path.has(neighbour)) stack.push([neighbour, 'explore']); } } console.log('Path: ' + JSON.stringify(Array.from(path))); return post_order; } var g = { '(1,1)': ['(1,2)','(2,2)'], '(1,2)': ['(1,3)'], '(1,3)': ['(1,2)','(2,3)'], '(2,2)': ['(3,3)'], '(2,3)': [], '(3,3)': ['(2,2)'], } /* (1,1) -&gt; (1,2) &lt;-&gt; (1,3) -&gt; (2,3) \ (2,2) &lt;-&gt; (3,3) */ console.log(JSON.stringify(f(g)));</code></pre> </div> </div> </p>
python|algorithm|graph|depth-first-search
1
1,904,670
48,485,522
Recover GET parameter from PasswordResetConfirmView
<p>I'm trying to recover a <code>GET</code> parameter from the Django template view <code>django.contrib.auth.PasswordResetConfirmView</code>. Basically when a user click on his password reset link (like <code>http://127.0.0.1:8000/commons/reset/MQ/4t8-210d1909d621e8b4c68e/?origin_page=/mypage/</code>) I want to be able to retrieve the <code>origin_page=/mypage/</code> argument. So far my <code>url.py</code> looks like this:</p> <pre><code>from django.urls import path from . import views app_name = 'commons' urlpatterns = [ path('reset/&lt;uidb64&gt;/&lt;token&gt;/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] </code></pre> <p>And my <code>views.py</code> like this:</p> <pre><code>from django.contrib.auth import views as auth_views class PasswordResetConfirmView(auth_views.PasswordResetConfirmView): template_name = 'commons/password_reset_confirm.html' success_url = '/commons/reset/done/' def get(self, request, *args, **kwargs): self.extra_context = { 'origin_page': request.GET.get('origin_page') } return super().get(request, *args, **kwargs) </code></pre> <p>As you can see I'm trying to get my <code>origin_page</code> with <code>'origin_page': request.GET.get('origin_page')</code> but it doesn't work, I get a <code>None</code> value. I even used the debugger to inspect every objects from the class/method but none of them seems to contains my <code>origin_page</code> variable. Any idea?</p>
<p>The <code>PasswordResetConfirmView</code> does an internal redirect which removes the token from the URL. Because of this, any query params you pass with the email also get removed. The line of code that does this is in the <code>dispatch</code> function of <code>PasswordResetConfirmView</code> which replaces the path with a constant: <a href="https://github.com/django/django/blob/master/django/contrib/auth/views.py#L280" rel="nofollow noreferrer">https://github.com/django/django/blob/master/django/contrib/auth/views.py#L280</a></p> <pre><code>redirect_url = self.request.path.replace(token, self.reset_url_token) </code></pre> <p>So you have the right idea that you need to subclass the <code>PasswordResetConfirmView</code> but I believe you need to alter the <code>dispatch</code> function, where the function is mostly the same, except add the original query param back to the <code>redirect_url</code>:</p> <pre><code># tack on whatever query params came with the email link redirect_url = f'{redirect_url}?{self.request.GET.urlencode()}' </code></pre>
python|django|django-2.0
0
1,904,671
66,882,302
empty element when using selenium webdriver
<p>I am trying to locate the following element using selenium webdriver:</p> <pre><code>&lt;div class=&quot;lv-product__details&quot;&gt;&lt;div class=&quot;lv-product__details-head&quot;&gt;&lt;span class=&quot;lv-product__details-sku&quot;&gt; M40712 &lt;/span&gt; &lt;div class=&quot;lv-product-add-to-wishlist&quot;&gt;&lt;button aria-label=&quot;Add to Wishlist&quot; aria-disabled=&quot;false&quot; tabindex=&quot;0&quot; class=&quot;lv-icon-button lv-product-add-to-wishlist__button&quot;&gt;&lt;svg focusable=&quot;false&quot; aria-hidden=&quot;true&quot; class=&quot;lv-icon&quot;&gt;&lt;use xlink:href=&quot;/_nuxt/icons.svg#sprite-navigation-wishlist-off&quot;&gt;&lt;/use&gt;&lt;/svg&gt;&lt;/button&gt;&lt;/div&gt;&lt;/div&gt; &lt;h1 class=&quot;lv-product__title&quot;&gt; Pochette Accessoires &lt;/h1&gt; &lt;div class=&quot;lv-product-variations&quot;&gt;&lt;button class=&quot;lv-product-variation-selector list-label-l lv-product-variations__selector&quot; aria-expanded=&quot;false&quot;&gt;&lt;span class=&quot;lv-product-variation-selector__title -text-is-medium&quot;&gt; Material </code></pre> <p>I have tried:</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options url = &quot;https://en.louisvuitton.com/eng-nl/products/pochette-accessoires-monogram-005656&quot; options = Options() options.headless = True driver = webdriver.Chrome('path/to/chromedriver', chrome_options=options) driver.get(url) elem = driver.find_element_by_class_name(&quot;lv-product__details&quot;) </code></pre> <p>or via Xpath</p> <pre><code>elem = driver.find_element_by_xpath('//*[@id=&quot;__layout&quot;]/div/div[2]/div[2]/div[1]/div[1]/div[2]') </code></pre> <p>but the elem is returned as an empty list. is there something that I am doing wrong / can do differently to access the contents of the website?</p>
<h2>I think you have formated your XPath incorrect</h2> <p>Try this</p> <pre><code>driver.find_element_by_xpath('/div/div[2]/div[2]/div[1]/div[1]/div[2]/div[3]') </code></pre> <p>Or this</p> <pre><code>driver.find_element_by_class_name(&quot;lv-icon-button lv-product-add-to-wishlist__button&quot;) </code></pre> <p>And try to import time</p> <pre><code>import time time.sleep(3) # To make sure everything loads before selenium starts to locate the element </code></pre>
python|html|selenium|web-scraping
1
1,904,672
4,106,896
Python: Adding Dictionary Items.
<p>When we add dictionary Items, </p> <p>we use <code>x.items()+y.items()</code>, but there was something I don't understand. </p> <p>for example </p> <p>if <code>x={2:2,1:3}</code> and <code>y={1:3,3:1}</code> <code>x.items()+y.items()</code> gives <code>{3:1,2:2,1:3}</code></p> <p>so, as you can see, the answer mathematically could have been <code>6x+2x^2+x^3</code>,</p> <p>but the dictionary gives <code>x^3+2x^2+3x</code>,</p> <p>can any one tell me any better method which works better?</p>
<p>Let's be clear what's going on here!</p> <pre><code>In [7]: x.items() Out[7]: [(1, 3), (2, 2)] In [8]: y.items() Out[8]: [(1, 3), (3, 1)] In [9]: x.items() + y.items() Out[9]: [(1, 3), (2, 2), (1, 3), (3, 1)] In [10]: dict(x.items() + y.items()) Out[10]: {1: 3, 2: 2, 3: 1} </code></pre> <p><code>items()</code> produces a list of (key, value) tuples, and <code>+</code> concatenates the lists. You can then make that list back into a dictionary, which will deal with duplicate keys by taking the last value with a given key. Since it's a duplicate value this time, it doesn't matter, but it could:</p> <pre><code>In [11]: z = {1:4, 3:1} In [12]: dict(x.items() + z.items()) Out[12]: {1: 4, 2: 2, 3: 1} </code></pre> <p>In which case the 1:3 entry is discarded...</p> <p>(Not clear what your analogy to polynomials is... If you <em>really</em> want to represent polynomials that add arithmetically, you might want to check out the <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a> class <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.poly1d.html" rel="nofollow">poly1d</a> or <code>collections.Counter</code> described by @adw.)</p>
python|dictionary
5
1,904,673
69,304,813
How can I make a matrix print in a specific way in python?
<p>I want to create a matrix thats N by N and that N is recieved as an input and when it prints its printed in a spiral. For example if the input is a 4 that means the matrix will be 4 by 4 and it will look like this when printed:</p> <pre><code>1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 </code></pre> <p>I know how to create the matrix and make it N by N what I do not know is how can I make it look like this. Is there any guide,tutorial or anything I can watch/read to get how to make more 2d array exercises?</p> <pre><code>def llenar_matriz(n): # Fills the matrix for r in range(n): fila = [] for c in range(n): fila.append(0) matriz.append(fila) return matriz def imprimir_matriz(matriz): # Prints the matrix filas = len(matriz) columnas = len(matriz[0]) for f in range(filas): for c in range(columnas): print (&quot;%3d&quot; %matriz[f][c], end=&quot;&quot;) print() # Main program lado = int(input(&quot;Ingrese el tamaño de la matriz: &quot;)) while lado &lt; 1: print(&quot;Tamaño inválido. Debe ser mayor que 0&quot;) lado = int(input(&quot;Ingrese el tamaño de la matriz: &quot;)) matriz = [] llenar_matriz(lado) imprimir_matriz(matriz) </code></pre> <p>This is my code atm and all it does is create a matrix of N by N, fills it with 0's and prints it</p>
<p><strong>Algorithm</strong> :Let the array have R rows and C columns. seen[r] denotes that the cell on the r-th row and c-th column was previously visited. Our current position is (r, c), facing direction di, and we want to visit R x C total cells.</p> <p>As we move through the matrix, our candidate’s next position is (cr, cc). If the candidate is in the bounds of the matrix and unseen, then it becomes our next position; otherwise, our next position is the one after performing a clockwise turn. <br> Code:</p> <pre><code>def spiralOrder(matrix): ans = [] if (len(matrix) == 0): return ans R = len(matrix) C = len(matrix[0]) seen = [[0 for i in range(C)] for j in range(R)] dr = [0, 1, 0, -1] dc = [1, 0, -1, 0] r = 0 c = 0 di = 0 # Iterate from 0 to R * C - 1 for i in range(R * C): ans.append(matrix[r]) seen[r] = True cr = r + dr[di] cc = c + dc[di] if (0 &lt;= cr and cr &lt; R and 0 &lt;= cc and cc &lt; C and not(seen[cr][cc])): r = cr c = cc else: di = (di + 1) % 4 r += dr[di] c += dc[di] return ans # Driver code a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] for x in spiralOrder(a): print(x, end=&quot; &quot;) print() </code></pre> <p>This is a Pic of how it works: <a href="https://i.stack.imgur.com/WePml.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WePml.png" alt="enter image description here" /></a></p>
python|arrays|matrix
0
1,904,674
48,205,276
Can not import package installed in anaconda in PyCharm
<p><code>pywin32</code> Package is installed in anaconda, when a package is imported it gives an error in pycharm. I am using the anaconda interpreter in pycharm. It gives the same error in spyder.</p> <pre><code>Traceback (most recent call last): File "C:/Users/zahid/PycharmProjects/untitled3/test.py", line 1, in &lt;module&gt; from pywinauto.application import Application ModuleNotFoundError: No module named 'pywinauto' </code></pre> <p><a href="https://i.stack.imgur.com/4TASB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4TASB.jpg" alt="Anaconda Terminal"></a> <a href="https://i.stack.imgur.com/HGJl0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HGJl0.jpg" alt="PyCharm image"></a> Kindly help to resolve issue.</p>
<p>You have not installed the <a href="https://github.com/pywinauto/pywinauto" rel="nofollow noreferrer">pywinauto</a> module.</p> <p>Use</p> <pre><code>pip install pywinauto </code></pre> <p>to install it.</p>
python|pycharm|anaconda
1
1,904,675
48,216,417
Formatting datetimes without two digits in month and day?
<p>I have a dataframe that has a particular column with datetimes in a format outputted in the following format:</p> <pre><code>df['A'] 1/23/2008 15:41 3/10/2010 14:42 10/14/2010 15:23 1/2/2008 11:39 4/3/2008 13:35 5/2/2008 9:29 </code></pre> <p>I need to convert <code>df['A']</code> into <code>df['Date']</code>, <code>df['Time']</code>, and <code>df['Timestamp']</code>.</p> <p>I tried to first convert <code>df['A']</code> to a datetime by using</p> <pre><code>df['Datetime'] = pd.to_datetime(df['A'],format='%m/%d/%y %H:%M') </code></pre> <p>from which I would've created my three columns above, but my formatting codes for <code>%m/%d</code> do not pick up the single digit month and days.</p> <p>Does anyone know a quick fix to this?</p>
<p>There's a bug with your format. As @MaxU <a href="https://stackoverflow.com/questions/48216417/formatting-datetimes-without-two-digits-in-month-and-day/48216465#comment83414781_48216417">commented</a>, if you don't pass a <code>format</code> argument, then pandas will automagically convert your column to <code>datetime</code>.</p> <pre><code>df['Timestamp'] = pd.to_datetime(df['A']) </code></pre> <p>Or, to fix your code - </p> <pre><code>df['Timestamp'] = pd.to_datetime(df['A'], format='%m/%d/%Y %H:%M') </code></pre> <hr> <p>For your first query, use <code>dt.normalize</code> or, <code>dt.floor</code> (thanks, MaxU, for the suggestion!) -</p> <pre><code>df['Date'] = df['Timestamp'].dt.normalize() </code></pre> <p>Or,</p> <pre><code>df['Date'] = df['Timestamp'].dt.floor('D') </code></pre> <p>For your second query, use <code>dt.time</code>.</p> <pre><code>df['Time'] = df['Timestamp'].dt.time </code></pre> <p></p> <pre><code>df.drop('A', 1) Date Time Timestamp 0 2008-01-23 15:41:00 2008-01-23 15:41:00 1 2010-03-10 14:42:00 2010-03-10 14:42:00 2 2010-10-14 15:23:00 2010-10-14 15:23:00 3 2008-01-02 11:39:00 2008-01-02 11:39:00 4 2008-04-03 13:35:00 2008-04-03 13:35:00 5 2008-05-02 09:29:00 2008-05-02 09:29:00 </code></pre>
python|pandas|datetime|timestamp
2
1,904,676
48,112,022
How to return multiple values in Python map?
<p>I have a list of dicts:</p> <pre><code>&gt;&gt;&gt; adict = {'name': 'John Doe', 'age': 18} &gt;&gt;&gt; bdict = {'name': 'Jane Doe', 'age': 20} &gt;&gt;&gt; l = [] &gt;&gt;&gt; l.append(adict) &gt;&gt;&gt; l.append(bdict) &gt;&gt;&gt; l [{'age': 18, 'name': 'John Doe'}, {'age': 20, 'name': 'Jane Doe'}] </code></pre> <p>Now I want to split up the values of each dict per key. Currently, this is how I do that:</p> <pre><code>&gt;&gt;&gt; for i in l: ... name_vals.append(i['name']) ... age_vals.append(i['age']) ... &gt;&gt;&gt; name_vals ['John Doe', 'Jane Doe'] &gt;&gt;&gt; age_vals [18, 20] </code></pre> <p>Is it possible to achieve this via map? So that I don't have to call map multiple times, but just once?</p> <pre><code>name_vals, age_vals = map(lambda ....) </code></pre>
<p>A simple &amp; flexible way to do this is to "transpose" your list of dicts into a dict of lists. IMHO, this is easier to work with than creating a bunch of separate lists.</p> <pre><code>lst = [{'age': 18, 'name': 'John Doe'}, {'age': 20, 'name': 'Jane Doe'}] out = {} for d in lst: for k, v in d.items(): out.setdefault(k, []).append(v) print(out) </code></pre> <p><strong>output</strong></p> <pre><code>{'age': [18, 20], 'name': ['John Doe', 'Jane Doe']} </code></pre> <hr> <p>But if you really want to use <code>map</code> and separate lists on this there are several options. Willem has shown one way. Here's another.</p> <pre><code>from operator import itemgetter lst = [{'age': 18, 'name': 'John Doe'}, {'age': 20, 'name': 'Jane Doe'}] keys = 'age', 'name' age_lst, name_lst = [list(map(itemgetter(k), lst)) for k in keys] print(age_lst, name_lst) </code></pre> <p><strong>output</strong></p> <pre><code>[18, 20] ['John Doe', 'Jane Doe'] </code></pre> <p>If you're using Python 2, then the <code>list</code> wrapper around the <code>map</code> call isn't necessary, but it's a good idea to use it to make your code compatible with Python 3.</p>
python|functional-programming
7
1,904,677
17,254,947
Missing file when using Python 2.7.3 File.write() function
<p>If you are simply planning to write to a file using a python script as show below:</p> <pre><code>#!/usr/bin/python count = 1 fo = open('DbCount.txt', 'w') fo.write(str(count)) #fo.flush() fo.close() </code></pre> <p>The Dbcount.txt file which was placed in the same folder as the script(attempting to modify the Dbcount.txt). i dont see any change in the txt file and no error is shown by the interpreter, its very strange, any help ?</p>
<p>first of all, always use the with statement variant, that will always close the file, even on errors:</p> <pre><code>#!/usr/bin/python count = 1 with open('DbCount.txt', 'w') as fo: fo.write(str(count)) </code></pre> <p>then the <code>'w'</code> overwrites your file each time you write to it. If you want to append, use <code>'a'</code>.</p> <p>About your specific problem, did you look only in the directory of your script, or in the current directory you're calling the script from? As you wrote your code, the file's path you write to is relative to where you execute your code from.</p> <p>try:</p> <pre><code>import os count = 1 with open(os.path.join(os.path.dirname(__file__), 'DbCount.txt'), 'w') as fo: fo.write(str(count)) </code></pre> <p>then it should output <code>DbCount.txt</code> in the same path as your script.</p>
python
1
1,904,678
64,205,461
Why does pyfftw output zero?
<p>This must be a stupid question but I could not figure what is wrong by myself. I wanted to test pyfftw so I ran the following code:</p> <pre><code>import numpy as np import pyfftw a = np.random.randn(2,64,64) b = np.zeros(2,64,33)*np.complex(0.) pyfftw.FFTW(a,b,axes = (-2,-1), direction = 'FFTW_FORWARD') </code></pre> <p>I expect that the array <code>b</code> to be changed to the Fourier modes of array <code>a</code>. But it turns out that <code>b</code> is still all zeros. So what is wrong here? Can anyone give a hint? Thank you very much.</p> <p>Here is the follow up. Thanks AKX and Hamaza for pointing out that I should run the execute() method to get the FFT done. But Now there is another issue. I tried calling pyfftw in a self-defined function. The output shows that the input array is changed to all zeros.</p> <pre><code>def f2fh(f): ftmp = np.copy(f) nz,nx,ny = f.shape nky = ny nkx = (nx/2)+1 fh = np.zeros((nz,nky,nkx))*np.complex(0.) print 'ksksks',ftmp.shape,fh.shape,ftmp pyfftw.FFTW(ftmp, fh, axes = (-2,-1), direction = 'FFTW_FORWARD').execute() print 'a',ftmp return fh </code></pre> <p>The output is <a href="https://i.stack.imgur.com/mdlxd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mdlxd.png" alt="enter image description here" /></a></p> <p>Can anyone give a hint what is wrong this time? Thanks a lot...</p>
<p>You're not calling <code>execute()</code>. Via <a href="https://hgomersall.github.io/pyFFTW/pyfftw/pyfftw.html#pyfftw.FFTW" rel="nofollow noreferrer">the docs</a>:</p> <blockquote> <p>The actual FFT or iFFT is performed by calling the <a href="https://hgomersall.github.io/pyFFTW/pyfftw/pyfftw.html#pyfftw.FFTW.execute" rel="nofollow noreferrer"><code>execute()</code></a> method.</p> </blockquote> <blockquote> <p><code>execute()</code>: Execute the planned operation, taking the correct kind of FFT of the input array (i.e. FFTW.input_array), and putting the result in the output array (i.e. FFTW.output_array).</p> </blockquote> <p>You might also want to use the &quot;easier&quot; interfaces described <a href="https://hgomersall.github.io/pyFFTW/sphinx/tutorial.html#quick-and-easy-the-pyfftw-interfaces-module" rel="nofollow noreferrer">over here</a>:</p> <blockquote> <p><code>b = pyfftw.interfaces.numpy_fft.fft(a)</code></p> </blockquote>
python|pyfftw
3
1,904,679
64,421,481
PIP Configuration file could not be loaded - File contains no section headers
<p>I have installed Python 3.8.2 and Windows 10 on my computer. Whenever I use any command with pip like &quot;pip --version&quot; I get the following error message:</p> <p>Configuration file could not be loaded. File contains no section headers. file: 'C:\ProgramData\pip\pip.ini', line: 1</p> <p>This path doesn't even exist on my computer. This happens regardless of the (virtual) environment I'm in. I've searched for quite a while now and couldn't a solution find this specific problem. I'm fairly new to programming, so it's entirely possible that I'm doing something obvious wrong. Can anyone help here?</p>
<p>I got this error because my file was stored in a RTF format, had to make it plain text and then it worked!</p>
python|pip
1
1,904,680
70,613,492
completing a sparse timeline
<p>I have some sparse measurements of process status over time, looking like this:</p> <pre><code> tag 2022-01-15 2022-01-08 #Step3 2022-01-06 #Step2 2021-12-31 2021-12-28 #Step1 </code></pre> <p>... and I would like to transform them into a complete series that I can use to plot a timeline, looking like this:</p> <pre><code> tag 2021-12-28 #Step1 2021-12-29 #Step1 2021-12-30 #Step1 2021-12-31 #Step1 2022-01-01 #Step1 2022-01-02 #Step1 2022-01-03 #Step1 2022-01-04 #Step1 2022-01-05 #Step1 2022-01-06 #Step2 2022-01-07 #Step2 2022-01-08 #Step3 2022-01-09 #Step3 2022-01-10 #Step3 2022-01-11 #Step3 2022-01-12 #Step3 2022-01-13 #Step3 2022-01-14 #Step3 2022-01-15 #Step3 </code></pre> <p>The code below works, but it looks pretty ugly and I was wondering if there is a more elegant/efficient way to achieve this. Also, I get a <code>SettingWithCopyWarning</code> which I should be able to fix.</p> <p>Thanks!!</p> <pre><code>#! /usr/bin/env python3 import pandas as pd MY_SAMPLINGS = [ {'timestamp': '2022-01-15', 'tag': ''}, {'timestamp': '2022-01-08', 'tag': '#Step3'}, {'timestamp': '2022-01-06', 'tag': '#Step2'}, {'timestamp': '2021-12-31', 'tag': ''}, {'timestamp': '2021-12-28', 'tag': '#Step1'} ] myDates = [d['timestamp'] for d in MY_SAMPLINGS] dates = pd.date_range(myDates[-1],myDates[0]) df = pd.DataFrame(index=dates, columns=['tag']) for x in range((len(MY_SAMPLINGS)-1),0,-1): startTime = MY_SAMPLINGS[x]['timestamp'] endTime = MY_SAMPLINGS [x-1]['timestamp'] if (MY_SAMPLINGS[x]['tag']): myTag = MY_SAMPLINGS[x]['tag'] else: myTag = MY_SAMPLINGS[x+1]['tag'] df.loc[startTime:endTime]['tag'] = myTag print (df) </code></pre>
<p>Alright, I'll break everything down in small steps but it's just a few lines of code and is much more scalable than a loop.</p> <pre><code>import pandas as pd df = pd.DataFrame(MY_SAMPLINGS) </code></pre> <p>We first want to have the timestamps as an ordered time index.</p> <pre><code>df[&quot;timestamp&quot;] = pd.to_datetime(df[&quot;timestamp&quot;], format=&quot;%Y-%m-%d&quot;) df = df.set_index(&quot;timestamp&quot;).sort_index() </code></pre> <p>Which gives :</p> <pre><code> tag timestamp 2021-12-28 #Step1 2021-12-31 2022-01-06 #Step2 2022-01-08 #Step3 2022-01-15 </code></pre> <p>Then, resample on a daily basis and fill forward, meaning that any missing values generated by the resampling will take the value of the previous non-missing value.</p> <pre><code>df = df.resample(&quot;1D&quot;).ffill() </code></pre> <p>Which gives:</p> <pre><code> tag timestamp 2021-12-28 #Step1 2021-12-29 #Step1 2021-12-30 #Step1 2021-12-31 2022-01-01 2022-01-02 2022-01-03 2022-01-04 2022-01-05 2022-01-06 #Step2 2022-01-07 #Step2 2022-01-08 #Step3 2022-01-09 #Step3 2022-01-10 #Step3 2022-01-11 #Step3 2022-01-12 #Step3 2022-01-13 #Step3 2022-01-14 #Step3 2022-01-15 </code></pre> <p>Now, we still have all those empty strings, let's just consider them as empty and forward fill again.</p> <pre><code>df = df.replace('', pd.NA).ffill() </code></pre> <p>Now we're done :</p> <pre><code> tag timestamp 2021-12-28 #Step1 2021-12-29 #Step1 2021-12-30 #Step1 2021-12-31 #Step1 2022-01-01 #Step1 2022-01-02 #Step1 2022-01-03 #Step1 2022-01-04 #Step1 2022-01-05 #Step1 2022-01-06 #Step2 2022-01-07 #Step2 2022-01-08 #Step3 2022-01-09 #Step3 2022-01-10 #Step3 2022-01-11 #Step3 2022-01-12 #Step3 2022-01-13 #Step3 2022-01-14 #Step3 2022-01-15 #Step3 </code></pre>
python|pandas|performance
2
1,904,681
69,782,823
Understanding the PyTorch implementation of Conv2DTranspose
<p>I am trying to understand an example snippet that makes use of the PyTorch transposed convolution function, with documentation <a href="https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html" rel="nofollow noreferrer">here</a>, where in the docs the author writes:</p> <blockquote> <p>&quot;The padding argument effectively adds dilation * (kernel_size - 1) - padding amount of zero padding to both sizes of the input.&quot;</p> </blockquote> <p>Consider the snippet below where a <code>[1, 1, 4, 4]</code> sample image of all ones is input to a <code>ConvTranspose2D</code> operation with arguments <code>stride=2</code> and <code>padding=1</code> with a weight matrix of shape <code>(1, 1, 4, 4)</code> that has entries from a range between <code>1</code> and <code>16</code> (in this case <code>dilation=1</code> and <code>added_padding = 1*(4-1)-1 = 2</code>)</p> <pre><code>sample_im = torch.ones(1, 1, 4, 4).cuda() sample_deconv2 = nn.ConvTranspose2d(1, 1, 4, 2, 1, bias=False).cuda() sample_deconv2.weight = torch.nn.Parameter( torch.tensor([[[[ 1., 2., 3., 4.], [ 5., 6., 7., 8.], [ 9., 10., 11., 12.], [13., 14., 15., 16.]]]]).cuda()) </code></pre> <p>Which yields:</p> <pre><code>&gt;&gt;&gt; sample_deconv2(sample_im) tensor([[[[ 6., 12., 14., 12., 14., 12., 14., 7.], [12., 24., 28., 24., 28., 24., 28., 14.], [20., 40., 44., 40., 44., 40., 44., 22.], [12., 24., 28., 24., 28., 24., 28., 14.], [20., 40., 44., 40., 44., 40., 44., 22.], [12., 24., 28., 24., 28., 24., 28., 14.], [20., 40., 44., 40., 44., 40., 44., 22.], [10., 20., 22., 20., 22., 20., 22., 11.]]]], device='cuda:0', grad_fn=&lt;CudnnConvolutionTransposeBackward&gt;) </code></pre> <p>Now I have seen simple examples of transposed convolution without stride and padding. For instance, if the input is a <code>2x2</code> image <code>[[2, 4], [0, 1]]</code>, and the convolutional filter with one output channel is <code>[[3, 1], [1, 5]]</code>, then the resulting tensor of shape <code>(1, 1, 3, 3)</code> can be seen as the sum of the rightmost four matrices in the image below:</p> <p><a href="https://i.stack.imgur.com/vSZgS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vSZgS.png" alt="enter image description here" /></a></p> <p>The problem is I can't seem to find examples that use strides and/or padding in the same visualization. As per my snippet, I am having a very difficult time understanding how the padding is applied to the sample image, or how the stride works to get this output. Any insights appreciated, even just understanding how the <code>6</code> in the <code>(0,0)</code> entry or the <code>12</code> in the <code>(0,1)</code> entry of the resulting matrix are computed would be very helpful.</p>
<p>The output spatial dimensions of <a href="https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html" rel="noreferrer"><code>nn.ConvTranspose2d</code></a> are given by:</p> <pre><code>out = (x - 1)s - 2p + d(k - 1) + op + 1 </code></pre> <p>where <code>x</code> is the <em>input</em> spatial dimension and <code>out</code> the corresponding <em>output</em> size, <code>s</code> is the stride, <code>d</code> the dilation, <code>p</code> the padding, <code>k</code> the kernel size, and <code>op</code> the output padding.</p> <hr /> <p>If we keep the following operands:</p> <p><a href="https://i.stack.imgur.com/wnE5e.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wnE5e.png" alt="enter image description here" /></a></p> <p>For each value of the input, we compute a buffer (of the corresponding color) by calculating the product with each element of the kernel.</p> <p>Here are the visualizations for <code>s=1, p=0</code>, <code>s=1, p=1</code>, <code>s=2, p=0</code>, and <code>s=2, p=1</code>:</p> <ul> <li><code>s=1, p=0</code>: output is <code>3x3</code></li> </ul> <p><a href="https://i.stack.imgur.com/nQ9o7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nQ9o7.png" alt="enter image description here" /></a></p> <p>For the <strong>blue buffer</strong>, we have (1) <code>2*k_top-left = 2*3 = 6</code>; (2) <code>2*k_top-right = 2*1 = 2</code>; (3) <code>2*k_bottom-left = 2*1 = 2</code>; (4) <code>2*k_bottom-right = 2*5 = 10</code>.</p> <ul> <li><code>s=1, p=1</code>: output is <code>1x1</code></li> </ul> <p><a href="https://i.stack.imgur.com/BVmeD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BVmeD.png" alt="enter image description here" /></a></p> <ul> <li><code>s=2, p=0</code>: output is <code>4x4</code></li> </ul> <p><a href="https://i.stack.imgur.com/2HkjF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2HkjF.png" alt="enter image description here" /></a></p> <ul> <li><code>s=2, p=2</code>: output is <code>2x2</code></li> </ul> <p><a href="https://i.stack.imgur.com/IcfWj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IcfWj.png" alt="enter image description here" /></a></p>
pytorch|conv-neural-network
6
1,904,682
55,665,653
get nested list out of list after normalizing it
<p>I have to perform one function on my nested list i.e to normalize it but unfortunately I'm not getting the original nested list.</p> <p>I tried using list of list</p> <pre><code>x = [[7.334, 2.234234, 3.3454], [4.1232, 8.345], [2.435, 4.435, 6.453]] m = list(map(max, zip(*x))) n = list(map(min, zip(*x))) print(m) print(n) def get_normalize_value(s): t = list(zip(m, n)) c = [] for k in t: c.append(list(k)) for i in c: k, h = i v = (s-h)/(k-h) return round(v, 2) def get(): another_list = [[get_normalize_value(j)] for i in x for j in i] return another_list print(get()) </code></pre> <p>so what I get after this was</p> <blockquote> <p>[[1.0], [-0.04], [0.19], [0.34], [1.21], [0.0], [0.41], [0.82]]</p> </blockquote> <p>but I want it is nested as it was</p> <blockquote> <p>[[1.0, -0.04, 0.19],[ 0.34, 1.21],[0.0, 0.41, 0.82]]</p> </blockquote>
<p>I modified your <code>get</code> function to get this output:</p> <pre><code>def get(): result = [] for i in x: result.append([get_normalize_value(j) for j in i]) return result </code></pre> <p>Output:</p> <blockquote> <p>[[1.0, -0.04, 0.19], [0.34, 1.21], [0.0, 0.41, 0.82]]</p> </blockquote>
python-3.x
0
1,904,683
55,791,386
Handling multiple exceptions in CBV Django
<p>Is there a way I can handle both the exceptions from different models and still pass none as context individually. </p> <p>Views.py</p> <pre><code>class ProfilePage(DetailView): model = models.UserCreation context_object_name = 'profile' def get_context_data(self, *args, **kwargs): context = super(ProfilePage, self).get_context_data(*args, **kwargs) user = User.objects.get(username=UserCreation.objects.get(id=self.kwargs.get('pk'))) print(self.request.user,user,self.kwargs.get('pk')) try: context['data'] = ProfileData.objects.get( user=user) context['userdata'] = User.objects.get( username=user) context['creationdata'] = UserCreation.objects.get(user=user) context['friends'] = Friends.objects.get( user=self.request.user,added=user) context['sorted'] = sorted(chain(AddStatus.objects.filter(user=user), ImageLib.objects.filter(user=user)), key=lambda instance: instance.date, reverse=True) except ((ProfileData.DoesNotExist as e) or (Friends.DoesNotExistas as f)) : if e: context['data']= None elif f: context['friends'] = None return context </code></pre>
<p>Yes, you should use two <code>try</code>-<code>except</code> scopes. In fact it is better <em>not</em> to write long <code>try</code>-<code>except</code> scopes, since then it is no longer clear what triggers the exception. So you can implement this like:</p> <pre><code>try: context['data'] = ProfileData.objects.get( user=user) except ProfileData.DoesNotExist: context['data']= None context['userdata'] = User.objects.get( username=user) context['creationdata'] = UserCreation.objects.get( user=user) try: context['friends'] = Friends.objects.get( user=self.request.user,added=user) except Friends.DoesNotExist: context['friends'] = None context['sorted'] = sorted( chain(AddStatus.objects.filter(user=user), ImageLib.objects.filter(user=user)), key=lambda instance: instance.date, reverse=True ) </code></pre> <p>In case having <em>multiple</em> <code>ProfileData</code>s, etc. is not a problem, you can make use of <code>.first()</code> instead that will return <code>None</code> if there is no row to return:</p> <pre><code>context['data'] = ProfileData.objects.filter(user=user).first() context['userdata'] = User.objects.get(username=user) context['creationdata'] = UserCreation.objects.get(user=user) context['friends'] = Friends.objects.filter( user=self.request.user,added=user).first() context['sorted'] = sorted( chain(AddStatus.objects.filter(user=user), ImageLib.objects.filter(user=user)), key=lambda instance: instance.date, reverse=True ) </code></pre>
python|django
2
1,904,684
55,909,620
Capturing block over multiple lines using pyparsing
<p>Trying to parse multiple selections over a multi-line document. Want to capture all lines between each of the keywords. Here's an example:</p> <pre><code>Keyword 1: CAPTURE THIS TEXT Keyword 2: CAPTURE THIS TEXT Keyword 3: CAPTURE THIS TEXT CAPTURE THIS TEXT CAPTURE THIS TEXT Keyword 4 </code></pre> <p>I might also have</p> <pre><code>Keyword 1: CAPTURE THIS TEXT CAPTURE THIS TEXT Keyword 2: CAPTURE THIS TEXT Keyword 3: CAPTURE THIS TEXT CAPTURE THIS TEXT CAPTURE THIS TEXT CAPTURE THIS TEXT Keyword 4 </code></pre> <p>My code looks like</p> <pre><code>from pyparsing import * EOL = LineEnd().suppress() line = OneOrMore(Group(SkipTo(LineEnd()) + EOL)) KEYWORD_CAPTURE_AREA = Keyword("Keyword 1:").suppress() + line + Keyword("Keyword 2:").suppress() + line \ + Keyword("Keyword 3:").suppress() + line + Keyword("Keyword 4").suppress() </code></pre> <p>Current approach returns no results if my result goes across multiple lines. Assume that there should be a straightforward solution to this - just haven't found it.</p>
<p>The concept to learn with <code>pyparsing</code> is that each sub-expression runs on its own, not aware of any containing or following expressions. So when your <code>line</code> is to match one or more "skip to the end of the current line", it doesn't know that it should stop when it sees the next "Keyword" string, and so it predictably reads to the end of the string. Then when the parser moves on to look for "Keyword 2:", it is already well past that point, and so raises an exception.</p> <p>You need to tell <code>OneOrMore</code> that it should stop parsing if it finds a "Keyword" at the beginning of a line, even if that would ordinarily match the repeating expression. A reasonable detection of the end of a block might be the word "Keyword" if found at the beginning of a line. (You could make it more detailed and match <code>"Keyword" + integer + ":"</code> to make this really bulletproof.) Let's call this "start_of_block_marker":</p> <pre><code>start_of_block_marker = LineStart() + "Keyword" </code></pre> <p>To tell OneOrMore that this indicates a stop condition for its repetition, pass this expression as the <code>stopOn</code> argument:</p> <pre><code>line = OneOrMore(Group(SkipTo(LineEnd()) + EOL), stopOn=LineStart() + "Keyword") </code></pre> <p>Now this will parse all your strings, but you are grouping within the OneOrMore, when I think you really want all the substrings in a single group. Also, the blank line between 2 and 3 creates an extra empty line. Here is an improved version of line:</p> <pre><code>line = Optional(EOL) + Group(OneOrMore(SkipTo(LineEnd()) + EOL, stopOn=LineStart() + "Keyword")) </code></pre> <p>I put your two test strings in a list, and then use it as an argument to <code>runTests()</code>:</p> <pre><code>text1 = """\ Keyword 1: CAPTURE THIS TEXT CAPTURE THIS TEXT Keyword 2: CAPTURE THIS TEXT Keyword 3: CAPTURE THIS TEXT CAPTURE THIS TEXT CAPTURE THIS TEXT CAPTURE THIS TEXT Keyword 4""" text2 = """\ Keyword 1: CAPTURE THIS TEXT Keyword 2: CAPTURE THIS TEXT Keyword 3: CAPTURE THIS TEXT CAPTURE THIS TEXT CAPTURE THIS TEXT Keyword 4 """ KEYWORD_CAPTURE_AREA.runTests(tests) </code></pre> <p>Which prints (echoing each test, and then printing the parsed results):</p> <pre><code>Keyword 1: CAPTURE THIS TEXT CAPTURE THIS TEXT Keyword 2: CAPTURE THIS TEXT Keyword 3: CAPTURE THIS TEXT CAPTURE THIS TEXT CAPTURE THIS TEXT CAPTURE THIS TEXT Keyword 4 [['CAPTURE THIS TEXT', 'CAPTURE THIS TEXT'], ['CAPTURE THIS TEXT'], ['CAPTURE THIS TEXT', 'CAPTURE THIS TEXT', 'CAPTURE THIS TEXT', 'CAPTURE THIS TEXT']] [0]: ['CAPTURE THIS TEXT', 'CAPTURE THIS TEXT'] [1]: ['CAPTURE THIS TEXT'] [2]: ['CAPTURE THIS TEXT', 'CAPTURE THIS TEXT', 'CAPTURE THIS TEXT', 'CAPTURE THIS TEXT'] Keyword 1: CAPTURE THIS TEXT Keyword 2: CAPTURE THIS TEXT Keyword 3: CAPTURE THIS TEXT CAPTURE THIS TEXT CAPTURE THIS TEXT Keyword 4 [['CAPTURE THIS TEXT'], ['CAPTURE THIS TEXT'], ['CAPTURE THIS TEXT', 'CAPTURE THIS TEXT', 'CAPTURE THIS TEXT']] [0]: ['CAPTURE THIS TEXT'] [1]: ['CAPTURE THIS TEXT'] [2]: ['CAPTURE THIS TEXT', 'CAPTURE THIS TEXT', 'CAPTURE THIS TEXT'] </code></pre> <p>If there is an error in the results, <code>runTests()</code> will display the problem line and location, and give the <code>pyparsing</code> error message.</p>
python|pyparsing
3
1,904,685
66,673,718
Include stderr and stdout when logging in python
<p>Having the following logging:</p> <pre class="lang-py prettyprint-override"><code>log_name = pd.datetime.now().date().strftime(format=&quot;%Y-%m-%d&quot;)+&quot;.log&quot; #Current day log_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))+&quot;/logs/&quot; #Path logging.basicConfig(filename=log_path+log_name,filemode=&quot;a&quot;,level = logging.INFO) </code></pre> <p>is there a way to catch &quot;Unknown&quot; exceptions (such as <code>pd.to_sql</code> errors due to e.g typo in the column name) and write them to the same logger file specified in <code>logging.basicConfig</code> without having try/catches all over the place?</p>
<p>Most of the times i use a combination of traceback library(standard) and a very big try-except clause under lets say main() function.So any uncaught error can be logged without special treatment. I hope fits your needs. Example:</p> <pre><code>import logging import traceback try: main() except: logger.warning(traceback.format_exc()) </code></pre>
python|error-logging
1
1,904,686
66,544,851
Using Behave to test asyncio application
<p>Is it possible to test an application based on <code>asyncio</code> events? If not, what's a testing strategy for intra-process event bus testing in python?</p> <p>My application is based on <a href="https://pyee.readthedocs.io" rel="nofollow noreferrer">pyee</a> using an event-bus to communicate between systems and <a href="https://sismic.readthedocs.io/en/latest/" rel="nofollow noreferrer">sismic</a> as the state machine.</p> <p>In my application, I start it using <code>aiorun</code> as follows:</p> <pre class="lang-py prettyprint-override"><code>from aiorun import run async def main(): app = TestApplication() await shutdown_waits_for(app.cleanup()) run(main()) </code></pre> <p>In this case, <code>TestApplication</code> is a testing stub that is doing the event routing between the state machine and various sub-systems listening to the event bus.</p> <p>What I'm trying to do is test the communication between systems. To run, the <code>GuiApplication</code> has to be running in the event loop, so a give step definition (that isn't working) would be something like this:</p> <pre class="lang-py prettyprint-override"><code>@when('I wait for message {message} to be fired containing {key}=&quot;{value}&quot;') @then('message {message} is fired containing {key}=&quot;{value}&quot;') @async_run_until_complete(timeout=1.2) async def step_impl5(context, message, key=None, value=None): dict = {} if key: dict[key] = value ta = TestApplication() await ta.wait_for_message(message, dict) </code></pre> <p>However, the above terminates with <code>RuntimeError: This event loop is already running</code></p> <p>I've has a bit of success using <a href="https://github.com/erdewit/nest_asyncio" rel="nofollow noreferrer">nest_asyncio</a>:</p> <pre class="lang-py prettyprint-override"><code>import nest_asyncio nest_asyncio.apply() </code></pre> <p>but this doesn't seem right either.</p> <p>In short, how can I utilize the existing event loop for testing, or can I?</p>
<p>You have two step decorators, <code>@when</code> and <code>@then</code>, for the same step implementation. There should only be one per step.</p> <pre><code>@when('I wait for message {message} to be fired containing {key}=&quot;{value}&quot;') def step_impl4(context, message, key=None, value=None): # set up context pass @then('message {message} is fired containing {key}=&quot;{value}&quot;') @async_run_until_complete(timeout=1.2) async def step_impl5(context, message, key=None, value=None): dict = {} if context.key: dict[key] = context.value ta = TestApplication() await ta.wait_for_message(message, dict) </code></pre>
python|python-asyncio|python-behave
0
1,904,687
64,956,290
how to scrape the text body from multiple pages based on urls in a txt file
<p>I tried to write a code that calls several URLs and then saves the entire scraped text in a txt file, but I can not figure out where to implement a loop function without breaking everything.</p> <p>that's how the code looks right now:</p> <pre><code>import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent from dhooks import Webhook, Embed def getReadMe(): with open('urls.txt','r') as file: return file.read() def getHtml(readMe): ua = UserAgent() header = {'user-agent':ua.random} response = requests.get(readMe,headers=header,timeout=3) response.raise_for_status() return response.content readMe = getReadMe() print(readMe) html = getHtml(readMe) soup = BeautifulSoup(html, 'html.parser') text = soup.find_all(text=True) output ='' blacklist = [ '[document]', 'noscript', 'header', 'html', 'meta', 'head', 'input', 'script', 'style' ] for t in text: if t.parent.name not in blacklist: output += '{} '.format(t) print(output) with open(&quot;copy.txt&quot;, &quot;w&quot;) as file: file.write(str(output)) </code></pre>
<pre><code>import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent from dhooks import Webhook, Embed def getReadMe(): with open('urls.txt','r') as file: return file.read() def getHtml(readMe): ua = UserAgent() header = {'user-agent':ua.random} response = requests.get(readMe,headers=header,timeout=3) response.raise_for_status() return response.content readMe = getReadMe() print(readMe) for line in readMe: html = getHtml(line) soup = BeautifulSoup(html, 'html.parser') text = soup.find_all(text=True) output ='' blacklist = [ '[document]', 'noscript', 'header', 'html', 'meta', 'head', 'input', 'script', 'style' ] for t in text: if t.parent.name not in blacklist: output += '{} '.format(t) print(output) #the option a makes u append the new data to the file with open(&quot;copy.txt&quot;, &quot;a&quot;) as file: file.write(str(output)) </code></pre> <p>Try this one and see if it works.</p>
python|python-3.x|web-scraping|beautifulsoup
1
1,904,688
65,015,919
How would I go about making a "Safe" .exe file with python?
<p>I've made a program to generate a random order of names and have converted it into a .exe file through Pyinstaller. It works fine but if I send it out, it will prompt the antivirus even though the file isn't harmful. I've tried looking for solutions in other places but they all require a form of payment, is there a free way I can go about doing this?</p>
<p>According to my knowledge,</p> <p>The quickest and safest way is to buy a windows certificate, this would make the file read completely safe even when sending it to another computer.</p> <p>Unfortunately, the 'free' options are either super complicated/uncertain/long, etc, and would only work locally.</p> <p>I suggest reading: <a href="https://softwareengineering.stackexchange.com/questions/191003/how-to-prevent-my-executable-being-treated-from-av-like-bad-or-virus">https://softwareengineering.stackexchange.com/questions/191003/how-to-prevent-my-executable-being-treated-from-av-like-bad-or-virus</a></p>
python|exe|pyinstaller
1
1,904,689
63,865,842
Run task on every 3rd and 8th minute in the day
<p>I would like to be able to run a task on the 3rd and 8th minute in the day between 7am-4pm local time. Also, it should only run Monday-Friday. I am writing this task in python and I am not sure what the best method of achieving this would be.</p> <p>I do <strong>not</strong> have access to cron (it will run on windows), and I have looked at multiple schedulers including <code>apscheduler </code> but unless I missed something I have not seen a way to achieve this.</p> <p>I read <a href="https://stackoverflow.com/questions/22715086/scheduling-python-script-to-run-every-hour-accurately">this post</a> where they talk about <code>apscheduler</code>, in reading that, and in the documentation, I only see a way to schedule the task in intervals or for a future time, but not on an exact time of the day.</p> <p>Any advice is appreciated. Thank you for your time.</p> <p><strong>Example of times to run</strong></p> <pre><code>7:03-Run 7:08-Run 7:13-Run 7:18-Run 7:23-Run 7:28-Run . . . etc </code></pre>
<p>Looks like you could use <a href="https://apscheduler.readthedocs.io/en/stable/modules/triggers/cron.html#module-apscheduler.triggers.cron" rel="nofollow noreferrer">apscheduler cron trigger type</a>, with schedule like this <a href="https://crontab.guru/#3,8,13,18,23,28_7-16_*_*_1-5" rel="nofollow noreferrer"><code>3,8,13,18,23,28,3 7-16 * * 1-5</code></a></p>
python|python-3.x|scheduled-tasks|scheduler|scheduling
1
1,904,690
62,874,000
How can I print 3 different types of values in a sorted 2d list from a text file?
<p>I have a text file where it is written the name of a person, num. pressups and num. pullups. This is the text file. <a href="https://i.stack.imgur.com/1I9Ea.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1I9Ea.png" alt="enter image description here" /></a></p> <p>I need to sort the students in the number of pressups and pullups that they can do respectively. For example, Jack can do the most amount of pressups and pullups so he would be at the top for both categories.</p> <p>To solve this, I think I should make a 2D list however I am unsure of how to sort to append the values in a sorted way. This is the code that I have written so far.</p> <pre><code>opener = open(&quot;gymclub.txt&quot;, &quot;r&quot;) reader = opener.readline() listObjects = [] listNames = [] listPressups = [] listPullups = [] while reader!=&quot;&quot;: splitting=reader.split(&quot;,&quot;) name = splitting[0] press_ups = splitting[1] pull_ups = splitting[2] reader = opener.readline() print(name) print(press_ups) print(pull_ups) listNames.append(name) listPressups.append(press_ups) listPullups.append(pull_ups) listObjects.append(name) listObjects.append(press_ups) listObjects.append(pull_ups) print(listObjects) splitting2 = str(listObjects).split(&quot;\n&quot;) # print(splitting[1]) # print(splitting[2]) opener.close() </code></pre> <p>I would just like to know a method that would help me to solve this problem.</p>
<p>It's easier to do this with pandas</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;your.csv&quot;, columns=[&quot;name&quot;,&quot;pressups&quot;, &quot;pullups&quot;]) df.sort([&quot;pressups&quot;, &quot;pullups&quot;], ascending=[True, False]) </code></pre>
python|python-3.x
2
1,904,691
61,989,225
Machine Learning and perceptrons
<p>I'm new in python so take it easy with me.</p> <p>So I got a project to complete about perceptrons.</p> <p>They gave me a dataset containing about 1300 lines.From this dataset the perceptron will train it self to increase accuracy and return me a number.</p> <p>I need to input 804082 for example and the program return me a number and the accuracy percentage.</p> <p>I got no idea where to start been searching for tutorials and guides all over the web with no results.</p> <p>My question is can someone guide me or link me a tutorial? Every help is accepted. </p> <p>Thanks in advance!</p> <p>This is from the dataset:</p> <pre><code> INPUTS, RESULTS 804081, 2 804080, 31 804079, 38 804078, 68 804077, 15 804076, 54 804075, 68 804074, 29 804073, 4 804072, 46 </code></pre>
<p>Here's from medium a tutorial done in python and step-by-step with code explanation <a href="https://medium.com/@thomascountz/19-line-line-by-line-python-perceptron-b6f113b161f3" rel="nofollow noreferrer">19-line Line-by-line Python Perceptron</a></p>
python|neural-network
0
1,904,692
71,340,957
emulate Excel's COUNTIF in pandas
<p>One way COUNTIF is used in Excel is to count all the matches in a column based on a <strong>changing</strong> base column.</p> <p>Input:</p> <pre><code>df = pd.DataFrame( [['a', 'a'], ['b', ''], ['c', ''], ['d', ''], ['e', 'b'], ['f', ''], ['g', ''], ['h', 'c'], ['i', ''], ['j', ''], ['k', 'd'], ['a', ''], ['b', 'b']], columns=['X', 'Y'] ) </code></pre> <p>Desired result:</p> <pre><code>result = pd.DataFrame( [['a', 'a', 2], ['b', '', 0], ['c', '', 0], ['d', '', 0], ['e', 'b', 2], ['f', '', 0], ['g', '', 0], ['h', 'c', 1], ['i', '', 0], ['j', '', 0], ['k', 'd', 1], ['a', '', 0], ['b', 'b', 2]], columns=['X', 'Y', 'Z'] ) </code></pre> <p>Here, COUNTIF would be counting the number of a's in the first column, then the number of blanks in the first column, then the number of blanks in the first column, ..., then the number of b's in the first column, etc.</p> <p>Is there a way to construct that third column in pandas in a vectorized way without iterating through the second column?</p>
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>pandas.Series.map</code></a> and fill the missing values with zeros.</p> <pre><code>df['Z'] = df['Y'].map(df['X'].value_counts()).fillna(0).astype(int) </code></pre>
python|pandas
0
1,904,693
63,491,044
How i can write c_ numpy list to txt file?
<p>I'm making a parser for site.From site i took info (Name of manga, author, genres). It's all i added to c_ list</p> <pre><code> api = requests.get(f'https://henchan.pro/manga/new?offset={page_count}') soup = BeautifulSoup(api.content, 'lxml') title = [e.get_text() for e in soup.find_all('a', attrs={&quot;class&quot;: 'title_link'})] href = [e['href'] for e in soup.find_all('a', attrs={&quot;class&quot;: 'title_link'})] author = [e.get_text() for e in soup.find_all('h3', attrs={&quot;class&quot;: 'item2'})] original_work = [e.get_text() for e in soup.find_all('h3', attrs={&quot;class&quot;: 'original work'})] genres = [e.get_text() for e in soup.find_all('div', attrs={&quot;class&quot;: 'genre'})] except Exception as e: print(e) page_count += 20 _all = c_[title, href, author, original_work, genres] </code></pre> <p>At the output, i get: <a href="https://prnt.sc/u2buv6" rel="nofollow noreferrer">https://prnt.sc/u2buv6</a></p> <p>How can I record all this in the same form in a TXT file?</p> <p>P.S All my code:</p> <pre><code>import requests from bs4 import BeautifulSoup from numpy import c_ import os def get_manga(): page_count = 0 pages = int(input('Lead the number of pages: ')) for e in range(pages): try: api = requests.get(f'https://henchan.pro/manga/new?offset={page_count}') soup = BeautifulSoup(api.content, 'lxml') title = [e.get_text() for e in soup.find_all('a', attrs={&quot;class&quot;: 'title_link'})] href = [e['href'] for e in soup.find_all('a', attrs={&quot;class&quot;: 'title_link'})] author = [e.get_text() for e in soup.find_all('h3', attrs={&quot;class&quot;: 'item2'})] original_work = [e.get_text() for e in soup.find_all('h3', attrs={&quot;class&quot;: 'original work'})] genres = [e.get_text() for e in soup.find_all('div', attrs={&quot;class&quot;: 'genre'})] except Exception as e: print(e) page_count += 20 _all = c_[title, href, author, original_work, genres] for x in _all: print(f&quot;Title: {x[0]}\nLink: https://henchan.pro/manga{x[1]}\nAuthor: {x[2]}\nOriginal Work: {x[3]}\nGenres: {x[4]}\n&quot;) </code></pre> <p>get_manga()</p>
<p>Below is the code in your OP with a file output instead of the print.</p> <pre><code>import requests from bs4 import BeautifulSoup from numpy import c_ import os def get_manga(): with open(&quot;filename_goes_here.txt&quot;, 'w') as out_file: page_count = 0 pages = int(input('Lead the number of pages: ')) for e in range(pages): try: api = requests.get(f'https://henchan.pro/manga/new?offset={page_count}') soup = BeautifulSoup(api.content, 'lxml') title = [e.get_text() for e in soup.find_all('a', attrs={&quot;class&quot;: 'title_link'})] href = [e['href'] for e in soup.find_all('a', attrs={&quot;class&quot;: 'title_link'})] author = [e.get_text() for e in soup.find_all('h3', attrs={&quot;class&quot;: 'item2'})] original_work = [e.get_text() for e in soup.find_all('h3', attrs={&quot;class&quot;: 'original work'})] genres = [e.get_text() for e in soup.find_all('div', attrs={&quot;class&quot;: 'genre'})] except Exception as e: print(e) page_count += 20 _all = c_[title, href, author, original_work, genres] for x in _all: out_file.write(f&quot;Title: {x[0]}\nLink: https://henchan.pro/manga{x[1]}\nAuthor: {x[2]}\nOriginal Work: {x[3]}\nGenres: {x[4]}\n&quot;)) get_manga() </code></pre>
python|list|numpy|parsing
0
1,904,694
56,540,272
how to find how many elements inside a list/numpy array and plot_dtmf tone genrator_sum of sin graphs
<p>I am trying to plot "frames" list. But I can't correctly plot without knowing how many elements inside this frames list. or is there any other way to plot sum of sin graphs. Type of the frames is a list. But when I print it shows like a numpy array. I am using numpy sin values inside this list. when I count len of frames list, it shows as 1. But I need to find how many values inside this numpy array. also please suggest me any easier and good way to plot results.Purpose of the code is to generate dtmf tones 0-9 and plot sum of sin graphs. tones are generating but I am stuck in plotting part.</p> <pre class="lang-py prettyprint-override"><code>FORMAT = pyaudio.paFloat32 CHANNELS = 1 RATE = 44100 CHUNK = 1024 RECORD_SECONDS = 5 WAVE_OUTPUT_FILENAME = "dtmf.wav" p = pyaudio.PyAudio() def sine_wave(frequency, length, rate): length = int(length * rate) factor = float(frequency) * (math.pi * 2) / rate return np.sin(np.arange(length) * factor) def sine_sine_wave(f1, f2, length, rate): s1=sine_wave(f1,length,rate) s2=sine_wave(f2,length,rate) ss=s1+s2 sa=np.divide(ss, 2.0) return sa def play_tone(stream, frequency=440, length=0.10, rate=44100): frames = [] frames.append(sine_wave(frequency, length, rate)) chunk = np.concatenate(frames) * 0.25 stream.write(chunk.astype(numpy.float32).tostring()) def play_dtmf_tone(stream, digits, length=0.2, rate=44100): dtmf_freqs = {'1': (1209,697), '2': (1336, 697), '3': (1477, 697), '4': (1209,770), '5': (1336, 770), '6': (1477, 770), '7': (1209,852), '8': (1336, 852), '9': (1477, 852), '*': (1209,941), '0': (1336, 941), '#': (1477, 941)} dtmf_digits = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#'] if type(digits) is not type(''): digits=str(digits)[0] digits = ''.join ([dd for dd in digits if dd in dtmf_digits]) joined_chunks = [] print(digits) for digit in digits: digit=digit.upper() frames = [] frames.append(sine_sine_wave(dtmf_freqs[digit][0], dtmf_freqs[digit][1], length, rate)) chunk = np.concatenate(frames) * 0.25 joined_chunks.append(chunk) # fader section fade = 200 # 200ms fade_in = np.arange(0., 1., 1/fade) fade_out = np.arange(1., 0., -1/fade) chunk[:fade] = np.multiply(chunk[:fade], fade_in) # fade sample wave in chunk[-fade:] = np.multiply(chunk[-fade:], fade_out) # fade sample wave out time.sleep(0.1) X = np.array(joined_chunks, dtype='float32') # creates an one long array of tone samples to record stream.write(X.astype(np.float32).tostring()) # to hear tones list_test = frames N = 100 time_max = 1 d_time = time_max/N times = np.linspace(0, time_max,N) print(("frames :{}").format(frames)) print(type(frames)) print(len(frames)) plt.plot(times, frames) # record tone sequence float 32 array as a wave file section for i in range(0, int(RECORD_SECONDS)): waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb') waveFile.setnchannels(CHANNELS) waveFile.setsampwidth(p.get_sample_size(FORMAT)) waveFile.setframerate(RATE) waveFile.writeframes(X.astype(np.float32).tostring()) waveFile.close() if __name__ == '__main__': stream = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=1,frames_per_buffer=CHUNK) # Dial a telephone number. if len(sys.argv) != 2: user_input = input() sp_user_input = user_input.split() digits = str(np.array([sp_user_input])) # set random length of numbers to pluck from list a # below preps random list of numbers for inclusion into csv file digits=digits.replace("[",'') # replace characters with null digits=digits.replace("]",'') digits=digits.replace("'",'') digits=digits.replace("\n",'') digits=digits.replace(" ",'') # replace space with null print(digits) else: digits = sys.argv[2] play_dtmf_tone(stream, digits) stream.close() p.terminate() </code></pre>
<p>You are initializing your <code>frames</code> list inside your loop, therefore it is always 1 element long at the end.</p> <p>You should do instead:</p> <pre><code>(...) frames = [] for digit in digits: (...) frames.append(...) print(len(frames)) </code></pre>
python|numpy|dtmf
0
1,904,695
68,912,866
Updating dataframe with new dataframe, overwritting
<p>Although this question seems to be similar to previous ones, I could not have it solved with previous answers and I need help from experts.</p> <p>I am trying to update an existing data frame (df1) with data that is received from a different data frame (df2) into a new dataframe (df). Data frame df2 may have new column, new rows or new/blank data. Here is an example of what I am trying to accomplish.</p> <pre><code>df1 = pd.DataFrame(np.array([[1, 'A1', 'B1'], [2, 'A2', 'B2'], [3, 'A3', 'B3']]), columns=['ID', 'A', 'B']) df1 ID A B 0 1 A1 B1 1 2 A2 B2 2 3 A3 B3 df2 = pd.DataFrame(np.array([[1, 'A1X', 'B1X'], [2, 'A2X', ''], [4, 'A4', 'B4']]), columns=['ID', 'A', 'B']) df2 ID A B 0 1 A1X B1X 1 2 A2X NaN 2 4 A4 B4 </code></pre> <p>The desired output is:</p> <pre><code>df ID A B 0 1 A1X B1X 1 2 A2X B2 2 3 A3 B3 3 4 A4 B4 </code></pre> <p>Can you please help me?</p> <p>A novice Panda user</p>
<p>Try:</p> <pre><code>df1 = pd.DataFrame(np.array([[1, 'A1', 'B1'], [2, 'A2', 'B2'], [3, 'A3', 'B3']]), columns=['ID', 'A', 'B']) df2 = pd.DataFrame(np.array([[1, 'A1X', 'B1X'], [2, 'A2X', ''], [4, 'A4', 'B4']]), columns=['ID', 'A', 'B']) df1 = df1.set_index('ID').replace('', np.nan) df2 = df2.set_index('ID').replace('', np.nan) df_out = df2.combine_first(df1) print(df_out) </code></pre> <p>Output:</p> <pre><code> A B ID 1 A1X B1X 2 A2X B2 3 A3 B3 4 A4 B4 </code></pre>
python|pandas|dataframe
3
1,904,696
59,355,018
Having two different handlers for logging in python logging module
<p>I am trying to have two different handlers where one handler will print the logs on console and other different handler will print the logs on console. Conslole handler is given by one inbuilt python <code>modbus-tk</code> library and I have written my own file handlers.</p> <pre><code>LOG = utils.create_logger(name="console", record_format="%(message)s") . ---&gt; This is from modbus-tk library LOG = utils.create_logger("console", level=logging.INFO) logging.basicConfig(filename="log", level=logging.DEBUG) log = logging.getLogger("simulator") handler = RotatingFileHandler("log",maxBytes=5000,backupCount=1) log.addHandler(handler) </code></pre> <p>What I need:</p> <pre><code>LOG.info("This will print message on console") log.info("This will print message in file") </code></pre> <p>But problem is both the logs are getting printed on the console and both are going in file. I want only <code>LOG</code> to be printed on the console and <code>log</code> to be printed in the file.</p> <p>edited:</p> <p>Adding snippet from utils.create_logger</p> <pre><code>def create_logger(name="dummy", level=logging.DEBUG, record_format=None): """Create a logger according to the given settings""" if record_format is None: record_format = "%(asctime)s\t%(levelname)s\t%(module)s.%(funcName)s\t%(threadName)s\t%(message)s" logger = logging.getLogger("modbus_tk") logger.setLevel(level) formatter = logging.Formatter(record_format) if name == "udp": log_handler = LogitHandler(("127.0.0.1", 1975)) elif name == "console": log_handler = ConsoleHandler() elif name == "dummy": log_handler = DummyHandler() else: raise Exception("Unknown handler %s" % name) log_handler.setFormatter(formatter) logger.addHandler(log_handler) return logger </code></pre>
<p>I have an own customized logging module. I have modified a little and I think now it can be proper for your problem. It is totally configurable and it can handle more different handlers. </p> <p>If you want to combine the console and file logging, you only need to remove the return statement (I use this way).</p> <p>I have written comment to code for more understandable and You can found a test section in <code>if __name__ == "__main__": ...</code> statement.</p> <p><strong>Code:</strong></p> <pre><code>import logging import os # Custom logger class with multiple destinations class CustomLogger(logging.Logger): """ Customized Logger class from the original logging.Logger class. """ # Format for console log FORMAT = ( "[%(name)-30s][%(levelname)-19s] | %(message)-100s " "| (%(filename)s:%(lineno)d)" ) # Format for log file LOG_FILE_FORMAT = "[%(name)s][%(levelname)s] | %(message)s " "| %(filename)s:%(lineno)d)" def __init__( self, name, log_file_path=None, console_level=logging.INFO, log_file_level=logging.DEBUG, log_file_open_format="w", ): logging.Logger.__init__(self, name) consol_color_formatter = logging.Formatter(self.FORMAT) # If the "log_file_path" parameter is provided, # the logs will be visible only in the log file. if log_file_path: fh_formatter = logging.Formatter(self.LOG_FILE_FORMAT) file_handler = logging.FileHandler(log_file_path, mode=log_file_open_format) file_handler.setLevel(log_file_level) file_handler.setFormatter(fh_formatter) self.addHandler(file_handler) return # If the "log_file_path" parameter is not provided, # the logs will be visible only in the console. console = logging.StreamHandler() console.setLevel(console_level) console.setFormatter(consol_color_formatter) self.addHandler(console) if __name__ == "__main__": # pragma: no cover current_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_log.log") console_logger = CustomLogger(__file__, console_level=logging.INFO) file_logger = CustomLogger(__file__, log_file_path=current_dir, log_file_level=logging.DEBUG) console_logger.info("test_to_console") file_logger.info("test_to_file") </code></pre> <p><strong>Console output:</strong></p> <pre><code>&gt;&gt;&gt; python3 test.py [test.py][INFO ] | test_to_console | (test.py:55) </code></pre> <p><strong>Content of test_log.log file:</strong></p> <pre><code>[test.py][INFO] | test_to_file | test.py:56) </code></pre> <p>If something is not clear of you have question/remark, let me know and I will try to help.</p> <p><strong>EDIT:</strong></p> <p>If you change the <code>GetLogger</code> to <code>Logger</code> in your implementation, it will work.</p> <p><strong>Code:</strong></p> <pre><code>import logging def create_logger(name="dummy", level=logging.DEBUG, record_format=None): """Create a logger according to the given settings""" if record_format is None: record_format = "%(asctime)s\t%(levelname)s\t%(module)s.%(funcName)s\t%(threadName)s\t%(message)s" logger = logging.Logger("modbus_tk") logger.setLevel(level) formatter = logging.Formatter(record_format) if name == "console": log_handler = logging.StreamHandler() else: raise Exception("Wrong type of handler") log_handler.setFormatter(formatter) logger.addHandler(log_handler) return logger console_logger = create_logger(name="console") # logging.basicConfig(filename="log", level=logging.DEBUG) file_logger = logging.Logger("simulator") handler = logging.FileHandler("log", "w") file_logger.addHandler(handler) console_logger.info("info to console") file_logger.info("info to file") </code></pre> <p><strong>Console output:</strong></p> <pre><code>&gt;&gt;&gt; python3 test.py 2019-12-16 13:10:45,963 INFO test.&lt;module&gt; MainThread info to console </code></pre> <p><strong>Content of log file:</strong></p> <pre><code>info to file </code></pre>
python|logging
1
1,904,697
49,182,846
Pressing a button to have constant movement
<p>I followed an online tutorial to make a snake game and want some help to make some changes. As of now, <strong>holding</strong> the left or right arrow keys will cause the snake to move. Would it be able to make the snake move to the left or right with <strong>only a tap of the button</strong> so the user doesn't have to hold down the arrow keys?</p> <pre><code>question = True while not gameExit: #Movement for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: direction = "left" start_x_change = -block_size_mov start_y_change = 0 elif event.key == pygame.K_RIGHT: leftMov = False direction = "right" start_x_change = block_size_mov start_y_change = 0 </code></pre>
<p>The solution is to start off by storing the x,y coordinates of the sprite, set a modifier (increase or decrease amount) on keypress, and then add the modifier to the coordinates while looping. I've written a quick demo of such a system:</p> <pre><code>import pygame from pygame.locals import * pygame.init() # Set up the screen screen = pygame.display.set_mode((500,500), 0, 32) # Make a simple white square sprite player = pygame.Surface([20,20]) player.fill((255,255,255)) # Sprite coordinates start at the centre x = y = 250 # Set movement factors to 0 movement_x = movement_y = 0 while True: screen.fill((0,0,0)) for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_LEFT: movement_x = -0.05 movement_y = 0 elif event.key == K_RIGHT: movement_x = 0.05 movement_y = 0 elif event.key == K_UP: movement_y = -0.05 movement_x = 0 elif event.key == K_DOWN: movement_y = 0.05 movement_x = 0 # Modify the x and y coordinates x += movement_x y += movement_y screen.blit(player, (x, y)) pygame.display.update() </code></pre> <p>Note that you need to reset the x movement modifier to 0 when changing y, and vice-versa - otherwise you end up with interesting diagonal movements!</p> <p>For a snake game, you might want to modify the snake size as well as/instead of position - but you should be able to achieve something similar using the same structure.</p>
python-3.x|pygame
3
1,904,698
67,656,688
How to Get the currentProgram object in Ghidra?
<p>I want to write a python script that can extract and print objects from a ghidra project such as enums and structs and for that I need to call the DataTypeManager from the currentProgram object, but I'm not sure how to call currentProgram in a script that's not in the ghidra python terminal. Any suggestions or examples?</p>
<p>Found a solution: currentProgram can be called directly from the terminal with an import:</p> <pre><code>from __main__ import currentProgram </code></pre>
python|ghidra
1
1,904,699
34,920,352
Python Bokeh: Plotting same chart multiple times in gridplot
<p>I'm currently trying to get an overview of plots of data of different dates. To get a good feeling of the data I would like to plot relevant plots next to each other. This means I want to use the same plot multiple times in the gridplot command. However what I noticed is that when i use the same chart multiple times it will only show it once in the final .html file. My first attempt at solving this was to use a copy.deepcopy for the charts, but this gave the following error:</p> <pre><code>RuntimeError: Cannot get a property value 'label' from a LineGlyph instance before HasProps.__init__ </code></pre> <p>My approach has been as follows:</p> <pre><code>from bokeh.charts import Line, output_file, show, gridplot import pandas as pd output_file('test.html') plots = [] df = pd.DataFrame([[1,2], [3,1], [2,2]]) print(df) df.columns = ['x', 'y'] for i in range(10): plots.append(Line(df, x='x', y='y', title='Forecast: ' + str(i), plot_width=250, plot_height=250)) plot_matrix = [] for i in range(len(plots)-1, 2, -1): plot_matrix.append([plots[i-3], plots[i-2], plots[i]]) p = gridplot(plot_matrix) show(p) </code></pre> <p>The results of which is a an html page with a grid plot with a lot of missing graphs. Each graph is exactly shown once (instead of the 3 times required), which leads me to think that the gridplot does not like me using the same object multiple times. An obvious solve is to simply create every graph 3 times as a different object, which I will do for now, but not only is this inefficient, it also hurts my eyes when looking at my code. I'm hoping somebody has a more elegant solution for my problem.</p> <p>EDIT: made code runable</p>
<p>This is not possible. Bokeh plots (or Bokeh objects in general) may not be re-used in layouts. </p>
python|bokeh
0