qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
63,708,795
I'm receiving a string like this sentence **"Mr,Pavol,Bujna,has arrived"** from a server. To my Raspberry Pi with Python sockets... It's working well, but need to split the sentence to separate variables. What I have now: `message2 = 'Mr,Pavol,Bujna,has arrived'` What I need: ``` firstname = 'Pavol' surname = 'Bujna' arravingLeaving = 'has arrived' ``` How can I split the string variable to multiple variables when the string is a comma-separated? Raspberry Pi code. Important line is: `draw.text((10, 40), message2, font = font20, fill = 0)` ``` #!/usr/bin/python # -*- coding:utf-8 -*- import sys import os picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic') libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib') if os.path.exists(libdir): sys.path.append(libdir) import logging from waveshare_epd import epd2in13d import time from PIL import Image,ImageDraw,ImageFont import traceback from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM import sys PORT_NUMBER = 5000 SIZE = 1024 hostName = gethostbyname( '0.0.0.0' ) mySocket = socket( AF_INET, SOCK_DGRAM ) mySocket.bind( (hostName, PORT_NUMBER) ) #Set output log level logging.basicConfig(level=logging.DEBUG) while True: (data,addr) = mySocket.recvfrom(SIZE) message = str(data) #make string from data message2 = message[2:-1] #remove first (b), second (') and last (') character #try: logging.info("epd2in13d Demo") epd = epd2in13d.EPD() logging.info("init and Clear") epd.init() epd.Clear(0xFF) font15 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 15) font20 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 20) font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24) # Drawing on the Horizontal image logging.info("1.Drawing on the Horizontal image...") Himage = Image.new('1', (epd.height, epd.width), 255) # 255: clear the frame draw = ImageDraw.Draw(Himage) draw.text((150, 0), time.strftime('%H:%M'), font = font20, fill = 0) draw.text((10, 40), message2, font = font20, fill = 0) epd.display(epd.getbuffer(Himage)) time.sleep(2) ``` This code is for the ALPR system I made. Raspberry Pi has an e-ink display where it's showing who arrived. As the display is not long enough, I need to split the sentence into multiple lines, that's why I need multiple variables to work with. [![Raspberry Pi with E-ink display](https://i.stack.imgur.com/VsbeE.jpg)](https://i.stack.imgur.com/VsbeE.jpg)
2020/09/02
[ "https://Stackoverflow.com/questions/63708795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13082942/" ]
message2 = 'Mr,Pavol,Bujna,has arrived' ``` words=message2.split(',') firstname=words[1] lastname=words[2] arravingLeaving=words[3] ``` or u could use tuple unpacking as well
Thanks, I figured it out myself meanwhile. Splitting message2 string to multiple variables ``` title, firstName, lastName, arravingLeaving = message2.split(",") print(title) print(firstName) print(lastName) print(arravingLeaving) ``` Whole code: ``` #!/usr/bin/python # -*- coding:utf-8 -*- import sys import os picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic') libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib') if os.path.exists(libdir): sys.path.append(libdir) import logging from waveshare_epd import epd2in13d import time from PIL import Image,ImageDraw,ImageFont import traceback from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM import sys PORT_NUMBER = 5000 SIZE = 1024 hostName = gethostbyname( '0.0.0.0' ) mySocket = socket( AF_INET, SOCK_DGRAM ) mySocket.bind( (hostName, PORT_NUMBER) ) #Set output log level logging.basicConfig(level=logging.DEBUG) while True: (data,addr) = mySocket.recvfrom(SIZE) message = str(data) #make string from data message2 = message[2:-1] #remove first (b), second (') and last (') character #Splitting message2 string to multiple variables title, firstName, lastName, arravingLeaving = message2.split(",") print(title) print(firstName) print(lastName) print(arravingLeaving) #try: logging.info("epd2in13d Demo") epd = epd2in13d.EPD() logging.info("init and Clear") epd.init() epd.Clear(0xFF) font15 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 15) font20 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 20) font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24) # Drawing on the Horizontal image logging.info("1.Drawing on the Horizontal image...") Himage = Image.new('1', (epd.height, epd.width), 255) # 255: clear the frame draw = ImageDraw.Draw(Himage) draw.text((150, 0), time.strftime('%H:%M'), font = font20, fill = 0) draw.text((15, 0), title, font = font20, fill = 0) draw.text((10, 25), firstName, font = font20, fill = 0) draw.text((10, 50), lastName, font = font20, fill = 0) draw.text((10, 75), arravingLeaving, font = font20, fill = 0) epd.display(epd.getbuffer(Himage)) time.sleep(2) ``` [![Working prototype](https://i.stack.imgur.com/7sj4V.jpg)](https://i.stack.imgur.com/7sj4V.jpg)
13,256,735
In my application, I have one single thread that is performing very fast processing on log lines to produce a float value. There is usually only a single other thread performing slow reads on the values at intervals. Every so often, other threads can come and go and also perform once-off reads on those values. My question is about the necessity of a mutex (in cpython), for this specific case where the data is simply the most recent data available. It is not a critical value that must be in sync with anything else (or even the other fields being written at the same time). Just simply... what the value is when it is. That being said, I know I could easily add a lock (or a readers / write lock) to guard the update of the value, but I wonder if the overhead of the acquire/release in rapid succession for the course of an entire log (lets say average 5000 lines) is not worth it just to do shared resources "appropriately". Based on the docs on [What kinds of global value mutation are thread-safe?](http://docs.python.org/2/faq/library#what-kinds-of-global-value-mutation-are-thread-safe), these assignments should be atomic operations. Here is a basic example of the logic: ```py import time from random import random, choice, randint from threading import Thread class DataStructure(object): def __init__(self): self.f_val = 0.0 self.s_val = "" def slow_reader(data): """ Loop much more slowly and read values anywhere between 1 - 5 second intervals """ for _ in xrange(10): f_val = data.f_val # don't care about sync here s_val = data.s_val print f_val, s_val # in real code could be even 30 or 60 seconds time.sleep(randint(1,3)) def fast_writer(data): """ Update data extremely often """ for _ in xrange(20000): f_val, s_val = do_work() data.f_val = f_val # don't care about sync here data.s_val = s_val FLOAT_SRC = [random()*100 for _ in xrange(100)] STR_SRC = ['foo', 'bar', 'biz', 'baz'] def do_work(): time.sleep(0.001) return choice(FLOAT_SRC), choice(STR_SRC) if __name__ == "__main__": data = DataStructure() threads = [ Thread(target=slow_reader, args=(data,)), Thread(target=fast_writer, args=(data,)), ] for t in threads: t.daemon=True t.start() for t in threads: t.join() ``` This represents the fast log parser (actually being read via a PIPE) doing work on each line, and a slow periodic reader grabbing whatever are the current values at that moment. At any time, another once-read thread could come and go to grab those same values from the data structure. Is this a situation where a mutex in cpython is not needed at all? **Edit** To clarify a bit more... I don't even need the float and string fields to be in sync from the last write. It is ok if the scheduler decides to switch contexts between the float and string reads. I'm just wondering if I even need the overhead of a lock to simply read whatever value is assigned at any moment in time. My concern is regarding the fact that the writer is going to be looping, on an extremely fast operating, locking and unlocking a lock that is often un-contended. Effectively assume this is all I care about in the `reader`: ``` def slow_reader(data): for _ in xrange(10): f_val = data.f_val print f_val time.sleep(randint(1,3)) ```
2012/11/06
[ "https://Stackoverflow.com/questions/13256735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496445/" ]
Try this macro: ``` Sub ConsolidateRows() 'takes rows and consolidate one or many cells, based on one or many cells matching with above or below rows. Dim lastRow As Long, i As Long, j As Long Dim colMatch As Variant, colConcat As Variant '**********PARAMETERS TO UPDATE**************** Const strMatch As String = "A" 'columns that need to match for consolidation, separated by commas Const strConcat As String = "B" 'columns that need consolidating, separated by commas Const strSep As String = ", " 'string that will separate the consolidated values '*************END PARAMETERS******************* application.ScreenUpdating = False 'disable ScreenUpdating to avoid screen flashes colMatch = Split(strMatch, ",") colConcat = Split(strConcat, ",") lastRow = range("A" & Rows.Count).End(xlUp).Row 'get last row For i = lastRow To 2 Step -1 'loop from last Row to one For j = 0 To UBound(colMatch) If Cells(i, colMatch(j)) <> Cells(i - 1, colMatch(j)) Then GoTo nxti Next For j = 0 To UBound(colConcat) if len(Cells(i - 1, colConcat(j)))>0 then _ Cells(i - 1, colConcat(j)) = Cells(i - 1, colConcat(j)) & strSep & Cells(i, colConcat(j)) Next Rows(i).Delete nxti: Next application.ScreenUpdating = True 'reenable ScreenUpdating End Sub ```
The following VBA code should work for what you are trying to do. It assumes that your email addresses are in the range A2:A50000, so you can change this to fit your needs. If you are not too familiar with VBA, under the Developer Tab in Excel 2011 Mac, there should be an icon called Visual Basic Editor. Open VB and CMD+Click on the window pane and insert a new module. Then paste in the following code: ``` Sub combineData() Dim xCell As Range, emailRange As Range Dim tempRow(0 To 3) As Variant, allData() As Variant Dim recordCnt As Integer Set emailRange = Range("A2:A11") recordCnt = -1 'LOOP THROUGH EACH CELL AND ADD THE DATE TO AN ARRAY For Each xCell In emailRange 'IF THE CELL IS EQUAL TO THE ONE ABOVE IT, 'ADD THE PRODUCT NUMBER SEPARATED WITH A COMMA If xCell = xCell.Offset(-1, 0) Then tempRow(1) = tempRow(1) & ", " & xCell.Offset(0, 1).Value allData(recordCnt) = tempRow Else recordCnt = recordCnt + 1 If recordCnt = 0 Then ReDim allData(0 To recordCnt) Else ReDim Preserve allData(0 To recordCnt) End If tempRow(0) = xCell.Value tempRow(1) = xCell.Offset(0, 1).Value tempRow(2) = xCell.Offset(0, 2).Value tempRow(3) = xCell.Offset(0, 3).Value allData(recordCnt) = tempRow End If Next xCell 'CREATE A NEW WORKSHEET AND DUMP IN THE CONDENSED DATA Dim newWs As Worksheet, i As Integer, n As Integer Set newWs = ThisWorkbook.Worksheets.Add For i = 0 To recordCnt For n = 0 To 3 newWs.Range("A2").Offset(i, n) = allData(i)(n) Next n Next i End Sub ``` Then close VB, and click the "Macros" button under the Developer tab. Then run combineData. That should give you the result you're looking for. Let me know if you have any trouble!
53,910,919
I want get the name (first line only) from the below raw content. Can you please help me? I want to get just `RAM KUMAR` only from the raw text using python. Raw Content: ``` "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\nshri.babuji@shriresume.com, shri1.babuji@shriresume.com\n\nLinkedin.com/in/ramkumar \t\t\t\t \n\n\t\t\t\n\n \t \n\nSUMMARY\n\n\n\nHighly motivated, creative and versatile IT professional with 9.2 years of experience in Java, J2SE & J2EE and related technologies as Developer, Onsite/Offshore Coordinator and Project Lead.\n\nProficiency in Java, Servlets, Struts and the latest frameworks like JSF, EJB 3.0.\n\nKnowledge of Java, JSP, Servlet, EJB, JMS, Struts and spring, Hibernate, XML, Web Services.\n\nExperience in using MVC design pattern, Java, Servlets, JSP, JavaScript, Hibernate 3.0, Web Services (SOAP and Restful), HTML, JQuery, XML, Web Logic, JBOSS 4.2.3, SQL, PL/SQL, JUnit, and Apache-Tomcat, Linux.\n\nExtensive experience in developing various web based applications using Struts framework.\n\nExpertise in relational databases like Oracle, My SQL and SQL Server.\n\nExperienced in developing Web Based applications using Web Sphere 6.0 and Oracle 9i as a back end." ```
2018/12/24
[ "https://Stackoverflow.com/questions/53910919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3239174/" ]
No need to use regex, just simply do: ``` print(yourstring.split('\n')[0]) ``` Output: ``` RAM KUMAR ``` **Edit:** ``` with open(filename,'r') as f: print(f.read().split('\n')[0]) ```
Use [`split`](https://www.geeksforgeeks.org/python-string-split/) to do something like this perhaps: ``` txt_content = "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\nshri.babuji@shriresume.com, shri1.babuji@shriresume.com\n\nLinkedin.com/in/ramkumar \t\t\t\t \n\n\t\t\t\n\n \t \n\nSUMMARY\n\n\n\nHighly motivated, creative and versatile IT professional with 9.2 years of experience in Java, J2SE & J2EE and related technologies as Developer, Onsite/Offshore Coordinator and Project Lead.\n\nProficiency in Java, Servlets, Struts and the latest frameworks like JSF, EJB 3.0.\n\nKnowledge of Java, JSP, Servlet, EJB, JMS, Struts and spring, Hibernate, XML, Web Services.\n\nExperience in using MVC design pattern, Java, Servlets, JSP, JavaScript, Hibernate 3.0, Web Services (SOAP and Restful), HTML, JQuery, XML, Web Logic, JBOSS 4.2.3, SQL, PL/SQL, JUnit, and Apache-Tomcat, Linux.\n\nExtensive experience in developing various web based applications using Struts framework.\n\nExpertise in relational databases like Oracle, My SQL and SQL Server.\n\nExperienced in developing Web Based applications using Web Sphere 6.0 and Oracle 9i as a back end." print(txt_content.split('\n')[0]) # 'RAM KUMAR' ```
53,910,919
I want get the name (first line only) from the below raw content. Can you please help me? I want to get just `RAM KUMAR` only from the raw text using python. Raw Content: ``` "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\nshri.babuji@shriresume.com, shri1.babuji@shriresume.com\n\nLinkedin.com/in/ramkumar \t\t\t\t \n\n\t\t\t\n\n \t \n\nSUMMARY\n\n\n\nHighly motivated, creative and versatile IT professional with 9.2 years of experience in Java, J2SE & J2EE and related technologies as Developer, Onsite/Offshore Coordinator and Project Lead.\n\nProficiency in Java, Servlets, Struts and the latest frameworks like JSF, EJB 3.0.\n\nKnowledge of Java, JSP, Servlet, EJB, JMS, Struts and spring, Hibernate, XML, Web Services.\n\nExperience in using MVC design pattern, Java, Servlets, JSP, JavaScript, Hibernate 3.0, Web Services (SOAP and Restful), HTML, JQuery, XML, Web Logic, JBOSS 4.2.3, SQL, PL/SQL, JUnit, and Apache-Tomcat, Linux.\n\nExtensive experience in developing various web based applications using Struts framework.\n\nExpertise in relational databases like Oracle, My SQL and SQL Server.\n\nExperienced in developing Web Based applications using Web Sphere 6.0 and Oracle 9i as a back end." ```
2018/12/24
[ "https://Stackoverflow.com/questions/53910919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3239174/" ]
No need to use regex, just simply do: ``` print(yourstring.split('\n')[0]) ``` Output: ``` RAM KUMAR ``` **Edit:** ``` with open(filename,'r') as f: print(f.read().split('\n')[0]) ```
Since the question is tagged [regex](/questions/tagged/regex "show questions tagged 'regex'"), I am offering a regex-based solution for the same. Use the following expression: `^[^\n]+` [Demo](https://regex101.com/r/h40abu/1) All I am doing is matching everything except the `'\n'` charatcer from the beginning of the line. The first match will then be the result you are interested in.
53,910,919
I want get the name (first line only) from the below raw content. Can you please help me? I want to get just `RAM KUMAR` only from the raw text using python. Raw Content: ``` "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\nshri.babuji@shriresume.com, shri1.babuji@shriresume.com\n\nLinkedin.com/in/ramkumar \t\t\t\t \n\n\t\t\t\n\n \t \n\nSUMMARY\n\n\n\nHighly motivated, creative and versatile IT professional with 9.2 years of experience in Java, J2SE & J2EE and related technologies as Developer, Onsite/Offshore Coordinator and Project Lead.\n\nProficiency in Java, Servlets, Struts and the latest frameworks like JSF, EJB 3.0.\n\nKnowledge of Java, JSP, Servlet, EJB, JMS, Struts and spring, Hibernate, XML, Web Services.\n\nExperience in using MVC design pattern, Java, Servlets, JSP, JavaScript, Hibernate 3.0, Web Services (SOAP and Restful), HTML, JQuery, XML, Web Logic, JBOSS 4.2.3, SQL, PL/SQL, JUnit, and Apache-Tomcat, Linux.\n\nExtensive experience in developing various web based applications using Struts framework.\n\nExpertise in relational databases like Oracle, My SQL and SQL Server.\n\nExperienced in developing Web Based applications using Web Sphere 6.0 and Oracle 9i as a back end." ```
2018/12/24
[ "https://Stackoverflow.com/questions/53910919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3239174/" ]
Use [`split`](https://www.geeksforgeeks.org/python-string-split/) to do something like this perhaps: ``` txt_content = "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\nshri.babuji@shriresume.com, shri1.babuji@shriresume.com\n\nLinkedin.com/in/ramkumar \t\t\t\t \n\n\t\t\t\n\n \t \n\nSUMMARY\n\n\n\nHighly motivated, creative and versatile IT professional with 9.2 years of experience in Java, J2SE & J2EE and related technologies as Developer, Onsite/Offshore Coordinator and Project Lead.\n\nProficiency in Java, Servlets, Struts and the latest frameworks like JSF, EJB 3.0.\n\nKnowledge of Java, JSP, Servlet, EJB, JMS, Struts and spring, Hibernate, XML, Web Services.\n\nExperience in using MVC design pattern, Java, Servlets, JSP, JavaScript, Hibernate 3.0, Web Services (SOAP and Restful), HTML, JQuery, XML, Web Logic, JBOSS 4.2.3, SQL, PL/SQL, JUnit, and Apache-Tomcat, Linux.\n\nExtensive experience in developing various web based applications using Struts framework.\n\nExpertise in relational databases like Oracle, My SQL and SQL Server.\n\nExperienced in developing Web Based applications using Web Sphere 6.0 and Oracle 9i as a back end." print(txt_content.split('\n')[0]) # 'RAM KUMAR' ```
Since the question is tagged [regex](/questions/tagged/regex "show questions tagged 'regex'"), I am offering a regex-based solution for the same. Use the following expression: `^[^\n]+` [Demo](https://regex101.com/r/h40abu/1) All I am doing is matching everything except the `'\n'` charatcer from the beginning of the line. The first match will then be the result you are interested in.
28,465,477
I'm looking into how to compute as efficient as possible in python3 a dot product inside a double sum of the form: ``` import cmath for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(a*b for a,b in zip(x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` where r\_np is a array of several thousand triples, and x a constant triple. Timing for a length of `N=1000` triples is about `2.4s`. The same using numpy: ``` import numpy as np for j in range(0,N): for k in range(0,N): sum_np = np.add(sum_np, np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k])))) ``` is actually slower with a runtime of about `4.0s`. I presume this is due to no big vectorizing advantage, only the short 3 dot 3 is np.dot, which is eaten up by starting N^2 of those in the loop. However, a modest speedup over the first example I could gain by using plain python3 with map and mul: ``` from operator import mul for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(map(mul,x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` with a runtime about `2.0s` Attempts to either use an if condition to not calculate the case `j=k`, where ``` r_np[j] - r_np[k] = 0 ``` and thus the dot product also becomes 0, or splitting the sum up in two to achieve the same ``` for j in range(0,N): for k in range(j+1,N): ... for k in range(0,N): for j in range(k+1,N): ... ``` both made it even slower. So the whole thing scales with O(N^2), and I wonder if with some methods like sorting or other things one could get rid of the loops and to make it scale with O(N logN). The problem is that I need single digit second runtimes for a set of `N~6000` triples as I have thousands of those sums to compute. Otherwise I have to try scipy’s weave , numba, pyrex or python or go down the C path entirely… Thanks in advance for any help! **Edit:** this is how a data sample would look like: ``` # numpy arrays x_np = np.array([0,0,1], dtype=np.float64) N=1000 xy = np.multiply(np.subtract(np.random.rand(N,2),0.5),8) z = np.linspace(0,40,N).reshape(N,1) r_np = np.hstack((xy,z)) # in python format x = (0,0,1) r_p = r_np.tolist() ```
2015/02/11
[ "https://Stackoverflow.com/questions/28465477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519380/" ]
I used this to generate test data: ``` x = (1, 2, 3) r_p = [(i, j, k) for i in range(10) for j in range(10) for k in range(10)] ``` On my machine, this took `2.7` seconds with your algorithm. Then I got rid of the `zip`s and `sum`: ``` for j in range(0,N): for k in range(0,N): s = 0 for t in range(3): s += x[t] * (r_p[j][t] - r_p[k][t]) sum_p += cmath.exp(-1j * s) ``` This brought it down to `2.4` seconds. Then I noted that `x` is constant so: ``` x * (p - q) = x1*p1 - x1*q1 + x2*p2 - x2*q2 - ... ``` So I changed the generation code to: ``` x = (1, 2, 3) r_p = [(x[0] * i, x[1] * j, x[2] * k) for i in range(10) for j in range(10) for k in range(10)] ``` And the algorithm to: ``` for j in range(0,N): for k in range(0,N): s = 0 for t in range(3): s += r_p[j][t] - r_p[k][t] sum_p += cmath.exp(-1j * s) ``` Which got me to `2.0` seconds. Then I realized we can rewrite it as: ``` for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * (sum(r_p[j]) - sum(r_p[k]))) ``` Which, surprisingly, got me to `1.1` seconds, which I can't really explain - maybe some caching going on? Anyway, caching or not, you can precompute the sums of your triples and then you won't have to rely on the caching mechanism. I did that: ``` sums = [sum(a) for a in r_p] sum_p = 0 N = len(r_p) start = time.clock() for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * (sums[j] - sums[k])) ``` Which got me to `0.73` seconds. I hope this is good enough! **Update:** Here's one around `0.01` seconds with a single for loop. It seems mathematically sound, but it's giving slightly different results, which I'm guessing is due to precision issues. I'm not sure how to fix those, but I thought I'd post it in case you can live with the precision issues or someone knows how to fix them. Considering I'm using fewer `exp` calls than your initial code however, consider that maybe this is actually the more correct version, and your initial approach is the one with precision issues. ``` sums = [sum(a) for a in r_p] e_denom = sum([cmath.exp(1j * p) for p in sums]) sum_p = 0 N = len(r_p) start = time.clock() for j in range(0,N): sum_p += e_denom * cmath.exp(-1j * sums[j]) print(sum_p) end = time.clock() print(end - start) ``` **Update 2:** The same, except with less multiplications and a `sum` function call: ``` sum_p = e_denom * sum([np.exp(-1j * p) for p in sums]) ```
That double loop is a time killer in `numpy`. If you use vectorized array operations, the evaluation is cut to under a second. ``` In [1764]: sum_np=0 In [1765]: for j in range(0,N): for k in range(0,N): sum_np += np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k]))) In [1766]: sum_np Out[1766]: (2116.3316526447466-1.0796252780664872e-11j) In [1767]: np.exp(-1j * np.inner(x_np, (r_np[:N,None,:]-r_np[None,:N,:]))).sum((0,1)) Out[1767]: (2116.3316526447466-1.0796252780664872e-11j) ``` Timings: ``` In [1768]: timeit np.exp(-1j * np.inner(x_np, (r_np[:N,None,:]-r_np[None,:N,:]))).sum((0,1)) 1 loops, best of 3: 506 ms per loop In [1769]: %%timeit sum_np=0 for j in range(0,N): for k in range(0,N): sum_np += np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k]))) 1 loops, best of 3: 12.9 s per loop ``` replacing `np.inner` with `np.einsum` shaves 20% off the time ``` np.exp(-1j * np.einsum('k,ijk', x_np, r_np[:N,None,:]-r_np[None,:N,:])).sum((0,1)) ```
28,465,477
I'm looking into how to compute as efficient as possible in python3 a dot product inside a double sum of the form: ``` import cmath for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(a*b for a,b in zip(x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` where r\_np is a array of several thousand triples, and x a constant triple. Timing for a length of `N=1000` triples is about `2.4s`. The same using numpy: ``` import numpy as np for j in range(0,N): for k in range(0,N): sum_np = np.add(sum_np, np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k])))) ``` is actually slower with a runtime of about `4.0s`. I presume this is due to no big vectorizing advantage, only the short 3 dot 3 is np.dot, which is eaten up by starting N^2 of those in the loop. However, a modest speedup over the first example I could gain by using plain python3 with map and mul: ``` from operator import mul for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(map(mul,x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` with a runtime about `2.0s` Attempts to either use an if condition to not calculate the case `j=k`, where ``` r_np[j] - r_np[k] = 0 ``` and thus the dot product also becomes 0, or splitting the sum up in two to achieve the same ``` for j in range(0,N): for k in range(j+1,N): ... for k in range(0,N): for j in range(k+1,N): ... ``` both made it even slower. So the whole thing scales with O(N^2), and I wonder if with some methods like sorting or other things one could get rid of the loops and to make it scale with O(N logN). The problem is that I need single digit second runtimes for a set of `N~6000` triples as I have thousands of those sums to compute. Otherwise I have to try scipy’s weave , numba, pyrex or python or go down the C path entirely… Thanks in advance for any help! **Edit:** this is how a data sample would look like: ``` # numpy arrays x_np = np.array([0,0,1], dtype=np.float64) N=1000 xy = np.multiply(np.subtract(np.random.rand(N,2),0.5),8) z = np.linspace(0,40,N).reshape(N,1) r_np = np.hstack((xy,z)) # in python format x = (0,0,1) r_p = r_np.tolist() ```
2015/02/11
[ "https://Stackoverflow.com/questions/28465477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519380/" ]
I used this to generate test data: ``` x = (1, 2, 3) r_p = [(i, j, k) for i in range(10) for j in range(10) for k in range(10)] ``` On my machine, this took `2.7` seconds with your algorithm. Then I got rid of the `zip`s and `sum`: ``` for j in range(0,N): for k in range(0,N): s = 0 for t in range(3): s += x[t] * (r_p[j][t] - r_p[k][t]) sum_p += cmath.exp(-1j * s) ``` This brought it down to `2.4` seconds. Then I noted that `x` is constant so: ``` x * (p - q) = x1*p1 - x1*q1 + x2*p2 - x2*q2 - ... ``` So I changed the generation code to: ``` x = (1, 2, 3) r_p = [(x[0] * i, x[1] * j, x[2] * k) for i in range(10) for j in range(10) for k in range(10)] ``` And the algorithm to: ``` for j in range(0,N): for k in range(0,N): s = 0 for t in range(3): s += r_p[j][t] - r_p[k][t] sum_p += cmath.exp(-1j * s) ``` Which got me to `2.0` seconds. Then I realized we can rewrite it as: ``` for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * (sum(r_p[j]) - sum(r_p[k]))) ``` Which, surprisingly, got me to `1.1` seconds, which I can't really explain - maybe some caching going on? Anyway, caching or not, you can precompute the sums of your triples and then you won't have to rely on the caching mechanism. I did that: ``` sums = [sum(a) for a in r_p] sum_p = 0 N = len(r_p) start = time.clock() for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * (sums[j] - sums[k])) ``` Which got me to `0.73` seconds. I hope this is good enough! **Update:** Here's one around `0.01` seconds with a single for loop. It seems mathematically sound, but it's giving slightly different results, which I'm guessing is due to precision issues. I'm not sure how to fix those, but I thought I'd post it in case you can live with the precision issues or someone knows how to fix them. Considering I'm using fewer `exp` calls than your initial code however, consider that maybe this is actually the more correct version, and your initial approach is the one with precision issues. ``` sums = [sum(a) for a in r_p] e_denom = sum([cmath.exp(1j * p) for p in sums]) sum_p = 0 N = len(r_p) start = time.clock() for j in range(0,N): sum_p += e_denom * cmath.exp(-1j * sums[j]) print(sum_p) end = time.clock() print(end - start) ``` **Update 2:** The same, except with less multiplications and a `sum` function call: ``` sum_p = e_denom * sum([np.exp(-1j * p) for p in sums]) ```
Ok guys, thanks a lot for the help. IVlads last code that uses the identity `sum_j sum_k a[j]*a[k] = sum_j a[j] * sum_k a[k]` makes the biggest difference. This now scales also with less then O(N^2). Precalculating the dot product before the sum makes hpaulj's numpy suggestion exactly the same fast: ``` sum_np = 0 dotprods = np.inner(q_np,r_np) sum_rkexp = np.exp(1j * dotprods).sum() sum_np = sum_rkexp * np.exp(-1j * dotprods).sum() ``` both with a runtime about `0.0003s`. However, I found one more thing that gives another ~50% increase, instead of computing the exponential twice, I take the complex conjugate inside the sum: ``` sum_np = 0 dotprods = np.inner(q_np,r_np) rkexp = np.exp(1j * dotprods) sum_rkexp = rkexp.sum() sum_np = sum_rkexp * np.conj(rkexp).sum() ``` which runs at around `0.0002s`. Over my first attempts with non vectorized numpy that took `~4s`, this is a speedup of about `2*10^4`, and for my 'real data' arrays of `N~6000` which run about `125s` I now get `0.0005s`, which is an amazing speedup of about `2.5*10^5`. Thanks a lot, IVlad and hpaulj, learned a lot in the last day :) P.S. I'm amazed by how quick you guys answer with stuff that took me half a day to just follow up ;)
28,465,477
I'm looking into how to compute as efficient as possible in python3 a dot product inside a double sum of the form: ``` import cmath for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(a*b for a,b in zip(x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` where r\_np is a array of several thousand triples, and x a constant triple. Timing for a length of `N=1000` triples is about `2.4s`. The same using numpy: ``` import numpy as np for j in range(0,N): for k in range(0,N): sum_np = np.add(sum_np, np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k])))) ``` is actually slower with a runtime of about `4.0s`. I presume this is due to no big vectorizing advantage, only the short 3 dot 3 is np.dot, which is eaten up by starting N^2 of those in the loop. However, a modest speedup over the first example I could gain by using plain python3 with map and mul: ``` from operator import mul for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(map(mul,x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` with a runtime about `2.0s` Attempts to either use an if condition to not calculate the case `j=k`, where ``` r_np[j] - r_np[k] = 0 ``` and thus the dot product also becomes 0, or splitting the sum up in two to achieve the same ``` for j in range(0,N): for k in range(j+1,N): ... for k in range(0,N): for j in range(k+1,N): ... ``` both made it even slower. So the whole thing scales with O(N^2), and I wonder if with some methods like sorting or other things one could get rid of the loops and to make it scale with O(N logN). The problem is that I need single digit second runtimes for a set of `N~6000` triples as I have thousands of those sums to compute. Otherwise I have to try scipy’s weave , numba, pyrex or python or go down the C path entirely… Thanks in advance for any help! **Edit:** this is how a data sample would look like: ``` # numpy arrays x_np = np.array([0,0,1], dtype=np.float64) N=1000 xy = np.multiply(np.subtract(np.random.rand(N,2),0.5),8) z = np.linspace(0,40,N).reshape(N,1) r_np = np.hstack((xy,z)) # in python format x = (0,0,1) r_p = r_np.tolist() ```
2015/02/11
[ "https://Stackoverflow.com/questions/28465477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519380/" ]
That double loop is a time killer in `numpy`. If you use vectorized array operations, the evaluation is cut to under a second. ``` In [1764]: sum_np=0 In [1765]: for j in range(0,N): for k in range(0,N): sum_np += np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k]))) In [1766]: sum_np Out[1766]: (2116.3316526447466-1.0796252780664872e-11j) In [1767]: np.exp(-1j * np.inner(x_np, (r_np[:N,None,:]-r_np[None,:N,:]))).sum((0,1)) Out[1767]: (2116.3316526447466-1.0796252780664872e-11j) ``` Timings: ``` In [1768]: timeit np.exp(-1j * np.inner(x_np, (r_np[:N,None,:]-r_np[None,:N,:]))).sum((0,1)) 1 loops, best of 3: 506 ms per loop In [1769]: %%timeit sum_np=0 for j in range(0,N): for k in range(0,N): sum_np += np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k]))) 1 loops, best of 3: 12.9 s per loop ``` replacing `np.inner` with `np.einsum` shaves 20% off the time ``` np.exp(-1j * np.einsum('k,ijk', x_np, r_np[:N,None,:]-r_np[None,:N,:])).sum((0,1)) ```
Ok guys, thanks a lot for the help. IVlads last code that uses the identity `sum_j sum_k a[j]*a[k] = sum_j a[j] * sum_k a[k]` makes the biggest difference. This now scales also with less then O(N^2). Precalculating the dot product before the sum makes hpaulj's numpy suggestion exactly the same fast: ``` sum_np = 0 dotprods = np.inner(q_np,r_np) sum_rkexp = np.exp(1j * dotprods).sum() sum_np = sum_rkexp * np.exp(-1j * dotprods).sum() ``` both with a runtime about `0.0003s`. However, I found one more thing that gives another ~50% increase, instead of computing the exponential twice, I take the complex conjugate inside the sum: ``` sum_np = 0 dotprods = np.inner(q_np,r_np) rkexp = np.exp(1j * dotprods) sum_rkexp = rkexp.sum() sum_np = sum_rkexp * np.conj(rkexp).sum() ``` which runs at around `0.0002s`. Over my first attempts with non vectorized numpy that took `~4s`, this is a speedup of about `2*10^4`, and for my 'real data' arrays of `N~6000` which run about `125s` I now get `0.0005s`, which is an amazing speedup of about `2.5*10^5`. Thanks a lot, IVlad and hpaulj, learned a lot in the last day :) P.S. I'm amazed by how quick you guys answer with stuff that took me half a day to just follow up ;)
61,354,963
``` >>> 1/3 0.3333333333333333 >>> 1/3+1/3+1/3 1.0 ``` I can't understand why this is 1.0. Shouldn't it be `0.9999999999999999`? So I kind of came up with the solution that python has an automatic rounding for it's answer, but if than, the following results can't be explained... ``` >>> 1/3+1/3+1/3+1/3+1/3+1/3 1.9999999999999998 >>> (1/3+1/3+1/3)+(1/3+1/3+1/3) 2.0 ``` I thought rounding error occurred because there were only limited number of digits to use in the mantissa, and the exponent,(in floating point numbers) but 0.9999~~9 is not off the limit of the number of digits too.. Can somebody explain why these results came out like this?
2020/04/21
[ "https://Stackoverflow.com/questions/61354963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376385/" ]
This is one of the subtle points of IEEE-754 arithmetic. When you write: ```py >>> 1/3 0.3333333333333333 ``` the number you see printed is a "rounded" version of the number that is internally stored as the result of `1/3`. It's just what the Double -> String conversion in the printing process decided to show you. But you already knew that. Now you can ask, is there a way to find out what the difference is? Yes, use the `fractions` module: ```py >>> from fractions import Fraction >>> Fraction(1, 3) - Fraction(1/3) Fraction(1, 54043195528445952) ``` Ah, that's interesting. So it is slightly less than the actual value, and the difference is `1 / 54043195528445952`. This is, of course, expected. So, what happens when you "add" two of these together. Let's see: ```py >>> Fraction(2,3) - Fraction(1/3+1/3) Fraction(1, 27021597764222976) ``` Again, you're close to `2/3`rds, but still not quite there. Let's do the addition one more time: ```py >>> Fraction(1,1) - Fraction(1/3+1/3+1/3) Fraction(0, 1) ``` Bingo! with 3 of them, the representation is exactly `1`. Why is that? Well, in each addition you get a number that's close to what you think the answer should be, but the internal rounding causes the result to become a close-by number that's not what you had in mind. With three additions what your intuition tells you and what the internal rounding does match up. It is important to emphasize that the addition `1/3 + 1/3 + 1/3` does *not* produce a `1`; it just produces an internal value whose closest representation as an IEEE-754 double-precision floating point value is `1`. This is a subtle but important difference. Hope that helps!
This question may provide some answers to the floating point error [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) With the brackets, the compiler is breaking down the addition into smaller pieces, reducing the possibility of a floating point which is not supposed to be there to carry on and keep 'accumulating' the floating point error. Most likely when split into groups of 3, the compiler knows the sum will be 1 and add 1 + 1 together
61,354,963
``` >>> 1/3 0.3333333333333333 >>> 1/3+1/3+1/3 1.0 ``` I can't understand why this is 1.0. Shouldn't it be `0.9999999999999999`? So I kind of came up with the solution that python has an automatic rounding for it's answer, but if than, the following results can't be explained... ``` >>> 1/3+1/3+1/3+1/3+1/3+1/3 1.9999999999999998 >>> (1/3+1/3+1/3)+(1/3+1/3+1/3) 2.0 ``` I thought rounding error occurred because there were only limited number of digits to use in the mantissa, and the exponent,(in floating point numbers) but 0.9999~~9 is not off the limit of the number of digits too.. Can somebody explain why these results came out like this?
2020/04/21
[ "https://Stackoverflow.com/questions/61354963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376385/" ]
Most Python implementations use a binary floating-point format, most commonly the IEEE-754 binary64 format. This format has **no** decimal digits. It has 53 binary digits. When this format is used with round-to-nearest-ties-to-even, computing 1/3 yields 0.333333333333333314829616256247390992939472198486328125. Your Python implementation fails to show the full value by default; it shows “0.3333333333333333”, which misleads you. When this number is added to itself, the result is 0.66666666666666662965923251249478198587894439697265625. This result is exact; it has no rounding error. (That is, it has no new rounding error; it is exactly the sum of 0.333333333333333314829616256247390992939472198486328125 with itself.) When 0.333333333333333314829616256247390992939472198486328125 is added again, the real-number result does not fit in 53 bits. So the result must be rounded. This rounding happens to round upward, producing exactly 1. When 0.333333333333333314829616256247390992939472198486328125 is added again, the result again does not fit, and is rounded. This time, the rounding happens to be downward, and produces 1.3333333333333332593184650249895639717578887939453125. Subsequent additions produce 1.666666666666666518636930049979127943515777587890625 and then 1.9999999999999997779553950749686919152736663818359375, which your Python implementation displays as “1.9999999999999998”. When you group the arithmetic as `(1/3+1/3+1/3) + (1/3+1/3+1/3)`, then 1 is obtained for each parenthesized item, as explained above, and 1+1 is of course 2.
This question may provide some answers to the floating point error [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) With the brackets, the compiler is breaking down the addition into smaller pieces, reducing the possibility of a floating point which is not supposed to be there to carry on and keep 'accumulating' the floating point error. Most likely when split into groups of 3, the compiler knows the sum will be 1 and add 1 + 1 together
61,354,963
``` >>> 1/3 0.3333333333333333 >>> 1/3+1/3+1/3 1.0 ``` I can't understand why this is 1.0. Shouldn't it be `0.9999999999999999`? So I kind of came up with the solution that python has an automatic rounding for it's answer, but if than, the following results can't be explained... ``` >>> 1/3+1/3+1/3+1/3+1/3+1/3 1.9999999999999998 >>> (1/3+1/3+1/3)+(1/3+1/3+1/3) 2.0 ``` I thought rounding error occurred because there were only limited number of digits to use in the mantissa, and the exponent,(in floating point numbers) but 0.9999~~9 is not off the limit of the number of digits too.. Can somebody explain why these results came out like this?
2020/04/21
[ "https://Stackoverflow.com/questions/61354963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376385/" ]
Most Python implementations use a binary floating-point format, most commonly the IEEE-754 binary64 format. This format has **no** decimal digits. It has 53 binary digits. When this format is used with round-to-nearest-ties-to-even, computing 1/3 yields 0.333333333333333314829616256247390992939472198486328125. Your Python implementation fails to show the full value by default; it shows “0.3333333333333333”, which misleads you. When this number is added to itself, the result is 0.66666666666666662965923251249478198587894439697265625. This result is exact; it has no rounding error. (That is, it has no new rounding error; it is exactly the sum of 0.333333333333333314829616256247390992939472198486328125 with itself.) When 0.333333333333333314829616256247390992939472198486328125 is added again, the real-number result does not fit in 53 bits. So the result must be rounded. This rounding happens to round upward, producing exactly 1. When 0.333333333333333314829616256247390992939472198486328125 is added again, the result again does not fit, and is rounded. This time, the rounding happens to be downward, and produces 1.3333333333333332593184650249895639717578887939453125. Subsequent additions produce 1.666666666666666518636930049979127943515777587890625 and then 1.9999999999999997779553950749686919152736663818359375, which your Python implementation displays as “1.9999999999999998”. When you group the arithmetic as `(1/3+1/3+1/3) + (1/3+1/3+1/3)`, then 1 is obtained for each parenthesized item, as explained above, and 1+1 is of course 2.
This is one of the subtle points of IEEE-754 arithmetic. When you write: ```py >>> 1/3 0.3333333333333333 ``` the number you see printed is a "rounded" version of the number that is internally stored as the result of `1/3`. It's just what the Double -> String conversion in the printing process decided to show you. But you already knew that. Now you can ask, is there a way to find out what the difference is? Yes, use the `fractions` module: ```py >>> from fractions import Fraction >>> Fraction(1, 3) - Fraction(1/3) Fraction(1, 54043195528445952) ``` Ah, that's interesting. So it is slightly less than the actual value, and the difference is `1 / 54043195528445952`. This is, of course, expected. So, what happens when you "add" two of these together. Let's see: ```py >>> Fraction(2,3) - Fraction(1/3+1/3) Fraction(1, 27021597764222976) ``` Again, you're close to `2/3`rds, but still not quite there. Let's do the addition one more time: ```py >>> Fraction(1,1) - Fraction(1/3+1/3+1/3) Fraction(0, 1) ``` Bingo! with 3 of them, the representation is exactly `1`. Why is that? Well, in each addition you get a number that's close to what you think the answer should be, but the internal rounding causes the result to become a close-by number that's not what you had in mind. With three additions what your intuition tells you and what the internal rounding does match up. It is important to emphasize that the addition `1/3 + 1/3 + 1/3` does *not* produce a `1`; it just produces an internal value whose closest representation as an IEEE-754 double-precision floating point value is `1`. This is a subtle but important difference. Hope that helps!
50,120,062
I have a 1D `numpy` array. The difference between two succeeding values in this array is either one or larger than one. I want to cut the array into parts for every occurrence that the difference is larger than one. Hence: ``` arr = numpy.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) ``` should become ``` [array([77, 78, 79, 80]), array([90, 91, 92]), array([100, 101, 102, 103, 104])] ``` I have the following code that does the trick but I have the feeling I am being to complicated here. There has to be a better/more pythonic way. Anyone with a more elegant approach? ``` import numpy def split(arr, cut_idxs): empty_arr = [] for idx in range(-1, cut_idxs.shape[0]): if idx == -1: l, r = 0, cut_idxs[0] elif (idx != -1) and (idx != cut_idxs.shape[0] - 1): l, r = cut_idxs[idx] + 1, cut_idxs[idx + 1] elif idx == cut_idxs.shape[0] - 1: l, r = cut_idxs[-1] + 1, arr.shape[0] empty_arr.append(arr[l:r + 1]) return empty_arr arr = numpy.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) cuts = numpy.where(numpy.ediff1d(arr) > 2)[0] print split(arr, cuts) ```
2018/05/01
[ "https://Stackoverflow.com/questions/50120062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2776885/" ]
One Pythonic way would be - ``` np.split(arr, np.flatnonzero(np.diff(arr)>1)+1) ``` Sample run - ``` In [10]: arr Out[10]: array([ 77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) In [11]: np.split(arr, np.flatnonzero(np.diff(arr)>1)+1) Out[11]: [array([77, 78, 79, 80]), array([90, 91, 92]), array([100, 101, 102, 103, 104])] ``` Another with `slicing` - ``` In [16]: cut_idx = np.r_[0,np.flatnonzero(np.diff(arr)>1)+1,len(arr)] # Or np.flatnonzero(np.r_[True, np.diff(arr)>1, True]) In [17]: [arr[i:j] for i,j in zip(cut_idx[:-1],cut_idx[1:])] Out[17]: [array([77, 78, 79, 80]), array([90, 91, 92]), array([100, 101, 102, 103, 104])] ```
Another way with slicing, getting the appropriate indices using `np.diff`: ``` import numpy as np def split(arr): idx = np.pad(np.where(np.diff(arr) > 1)[0]+1, (1,1), 'constant', constant_values = (0, len(arr))) return [arr[idx[i]: idx[i+1]] for i in range(len(idx)-1)] ``` Result: ``` arr = np.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) >>> split(arr) [array([77, 78, 79, 80]), array([90, 91, 92]), array([100, 101, 102, 103, 104])] ``` In your case, your slicing "map" `idx` ends up being: `array([ 0, 4, 7, 12])`, which is where the `diff` is greater than 1 (indices `4` and `7`), padded by a zero on the left, and the length of your array (`12`) on the right using [`np.pad`](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.pad.html) But `np.split`, as suggested by @Divakar seems to be the way to go
63,709,660
I'm trying to connect to an SFTP server using Python and Paramiko, but I'm getting this error (the same error occurs when I use pysftp): ```none starting thread (client mode): 0x17ccde50L Local version/idstring: SSH-2.0-paramiko_2.7.2 Remote version/idstring: SSH-2.0-OpenSSH_7.2 Connected (version 2.0, client OpenSSH_7.2) kex algos:[u'curve25519-sha256@libssh.org', u'ecdh-sha2-nistp256', u'ecdh-sha2-nistp384', u'ecdh-sha2-nistp521', u'diffie-hellman-group-exchange-sha256', u'diffie-hellman-group14-sha1'] server key:[u'ssh-rsa', u'rsa-sha2-512', u'rsa-sha2-256', u'ssh-dss', u'ecdsa-sha2-nistp256', u'ssh-ed25519'] client encrypt:[u'chacha20-poly1305@openssh.com', u'aes128-ctr', u'aes192-ctr', u'aes256-ctr', u'aes128-gcm@openssh.com', u'aes256-gcm@openssh.com'] server encrypt:[u'chacha20-poly1305@openssh.com', u'aes128-ctr', u'aes192-ctr', u'aes256-ctr', u'aes128-gcm@openssh.com', u'aes256-gcm@openssh.com'] client mac:[u'umac-64-etm@openssh.com', u'umac-128-etm@openssh.com', u'hmac-sha2-256-etm@openssh.com', u'hmac-sha2-512-etm@openssh.com', u'hmac-sha1-etm@openssh.com', u'umac-64@openssh.com', u'umac-128@openssh.com', u'hmac-sha2-256', u'hmac-sha2-512', u'hmac-sha1'] server mac:[u'umac-64-etm@openssh.com', u'umac-128-etm@openssh.com', u'hmac-sha2-256-etm@openssh.com', u'hmac-sha2-512-etm@openssh.com', u'hmac-sha1-etm@openssh.com', u'umac-64@openssh.com', u'umac-128@openssh.com', u'hmac-sha2-256', u'hmac-sha2-512', u'hmac-sha1'] client compress:[u'none', u'zlib@openssh.com'] server compress:[u'none', u'zlib@openssh.com'] client lang:[u''] server lang:[u''] kex follows?False Kex agreed: curve25519-sha256@libssh.org HostKey agreed: ssh-ed25519 Cipher agreed: aes128-ctr MAC agreed: hmac-sha2-256 Compression agreed: none kex engine KexCurve25519 specified hash_algo <built-in function openssl_sha256> Unknown exception: from_buffer() cannot return the address of the raw string within a str or unicode or bytearray object Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/paramiko/transport.py", line 2075, in run self.kex_engine.parse_next(ptype, m) File "/usr/lib/python2.7/site-packages/paramiko/kex_curve25519.py", line 64, in parse_next return self._parse_kexecdh_reply(m) File "/usr/lib/python2.7/site-packages/paramiko/kex_curve25519.py", line 129, in _parse_kexecdh_reply self.transport._activate_outbound() File "/usr/lib/python2.7/site-packages/paramiko/transport.py", line 2553, in _activate_outbound self.local_cipher, key_out, IV_out, self._ENCRYPT File "/usr/lib/python2.7/site-packages/paramiko/transport.py", line 1934, in _get_cipher return cipher.encryptor() File "/usr/lib64/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 126, in encryptor self.algorithm, self.mode File "/usr/lib64/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 487, in create_symmetric_encryption_ctx return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT) File "/usr/lib64/python2.7/site-packages/cryptography/hazmat/backends/openssl/ciphers.py", line 69, in __init__ iv_nonce = self._backend._ffi.from_buffer(mode.nonce) TypeError: from_buffer() cannot return the address of the raw string within a str or unicode or bytearray object ``` I was able to successfully connect to the SFTP server using: ```none sftp -oPort=22 xxxxx@10.132.x.x:/home ``` So I know the server exists and is accessible. My code in Python is simply this: ``` paramiko.util.log_to_file("filename.log") ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy()) ssh.connect(ftp_host, username=ftp_username, password=ftp_password, timeout=None) ``` And a few dependencies.. ```none asn1crypto @ file:///home/folder/app/utils/asn1crypto-1.2.0-py2.py3-none-any.whl bcrypt @ file:///home/folder/app/utils/bcrypt-3.1.6-cp27-cp27mu-manylinux1_x86_64.whl cffi==1.5.2 cryptography @ file:///home/folder/app/utils/cryptography-3.1-cp27-cp27mu-manylinux2010_x86_64.whl netmiko==2.3.2 paramiko @ file:///home/folder/app/utils/vendor/paramiko-2.7.2-py2.py3-none-any.whl ply==3.4 pyasn1==0.1.9 pycparser==2.19 PyNaCl @ file:///home/folder/app/utils/PyNaCl-1.3.0-cp27-cp27mu-manylinux1_x86_64.whl pyOpenSSL==16.0.0 six==1.9.0 ``` My question is, what does this error mean exactly and what is the best way to resolve it? I need to copy images to an SFTP, but can't quite connect. By the way, the server I'm running the Python is stuck on 2.7 and I'm not allowed to upgrade it. Also, it doesn't have access to the internet so I can't use things like apt-get. I install things by dragging and dropping zipped folders or .whl files. I just a matter of finding the correct combination of dependencies.
2020/09/02
[ "https://Stackoverflow.com/questions/63709660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5754267/" ]
This topic suggests that you may have obsolete dependencies: <https://github.com/paramiko/paramiko/issues/1027> [The solution by @bieli](https://github.com/paramiko/paramiko/issues/1027#issuecomment-374145838) seems to help many of those who face the problem: ``` sudo pip uninstall cryptography -y && sudo apt-get purge python3-cryptography && sudo apt-get autoremove && sudo pip3 install --upgrade cryptography ``` --- *If you cannot upgrade your dependencies, you can try using a different KEX. But in general, this may be dead end.* --- *Obligatory warning: Do not use `AutoAddPolicy` – You are losing a protection against [MITM attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack) by doing so. For a correct solution, see [Paramiko "Unknown Server"](https://stackoverflow.com/q/10670217/850848#43093883)*.
In the sample below, you may see absolute paths to a few of the dependencies because I'm running the Python script on a remote server without internet. Therefore, .whl files had to be copied from my PC to the remote server. Of these dependencies, "**cffi**" was upgraded to version 1.11.2 and eventually resolved the issue. If you find yourself having similar issue, try to find the best mixture of dependencies like so: ``` asn1crypto @ file:///home/badge_bridge/utils/asn1crypto-1.2.0-py2.py3-none-any.whl bcrypt @ file:///home/badge_bridge/utils/bcrypt-3.1.6-cp27-cp27mu-manylinux1_x86_64.whl cffi @ file:///home/badge_bridge/utils/vendor/cffi-1.11.2-cp27-cp27mu-manylinux1_x86_64.whl chrome-gnome-shell==0.0.0 cryptography @ file:///home/badge_bridge/utils/vendor/cryptography-2.1-cp27-cp27mu-manylinux1_x86_64.whl cupshelpers==1.0 ecdsa==0.6 enum34 @ file:///home/badge_bridge/utils/vendor/enum34-1.1.6-py2-none-any.whl idna==2.0 ipaddress==1.0.14 isc==2.0 netmiko==2.3.2 paramiko @ file:///home/badge_bridge/utils/vendor/paramiko-2.3.3-py2.py3-none-any.whl ply==3.4 pyasn1==0.1.9 pycparser==2.19 pycryptodome @ file:///home/badge_bridge/utils/vendor/pycryptodome-3.6.5-cp27-cp27mu-manylinux1_x86_64.whl pycups==1.9.66 pycurl==7.19.0 pygobject==3.20.1 PyNaCl @ file:///home/badge_bridge/utils/PyNaCl-1.3.0-cp27-cp27mu-manylinux1_x86_64.whl pyOpenSSL==16.0.0 pysftp==0.2.9 pysmbc==1.0.13 requests==2.11.1 six==1.13.0 ```
56,904,802
I want functions in a class to store their returned values in some data structure. For this purpose I want to use a decorator: ```py results = [] instances = [] class A: def __init__(self, data): self.data = data @decorator def f1(self, a, b): return self.data + a + b @decorator def f2(self, a): return self.data + a + 1 x = A(1) x.f1(1, 2) x.f2(3) print(results) ``` The question is, how to implement this decorator. The main idea is the following: ```py class Wrapper: def __init__(self, func): self.func = func def __call__(self, *args): res = self.func(*args) results.append(res) instances.append(args[0]) def decorator(func): return Wrapper(func) ``` But then I am getting an error message: ``` TypeError: f1() missing 1 required positional argument: 'b' ``` This question is similar to what other people asked ([How to decorate a method inside a class?](https://stackoverflow.com/questions/1367514/how-to-decorate-a-method-inside-a-class), [Python functools.wraps equivalent for classes](https://stackoverflow.com/questions/6394511/python-functools-wraps-equivalent-for-classes)), but it is not clear where to put `@functools.wraps` or to call `@functools.update_wrapped()` in my case.
2019/07/05
[ "https://Stackoverflow.com/questions/56904802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2015614/" ]
You will need to use `CodeIdTokenToken` response type, according to the [documentation](https://openid.net/specs/openid-connect-core-1_0.html#HybridAuthRequest) `options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken;`
I managed to fix this. To anyone that would encounter this issue, set the response type to **Code** to get both the id\_token and the access\_token. This will instruct Open ID Connect to use the authorization code flow. ``` options.ResponseType = OpenIdConnectResponseType.Code ```
61,039,847
I am making Exam app with kivy(python) and I have problem with getting correct answer. I have dictonary of translates from latin words to slovenian words exemple(Keys are latin words, values are slovenian words): ``` Dic = {"Aegrotus": "bolnik", "Aether": "eter"} ``` So the problem is when 2 or 3 latin words mean same as 1 sloveian word and vice versa. Exemple: ``` Dic = {("A", "ab"): "od", "Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": ("Dišeč", "Odišavljen")} ``` For example: [Exemple\_pic](https://i.stack.imgur.com/A8WTz.png) On image you see app, I have to translate "Agito" what means "stresam" So my question is how to check if its multiple keys what is its value. I hope you understand my question :).
2020/04/05
[ "https://Stackoverflow.com/questions/61039847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11590506/" ]
Firstly, you have to be able to get the text output from the app shown in the picture, then you use your dictionary to check it. And the way to design the dictionary makes it difficult to check. You should design it that way: key is only one string, and values is a list. For example: ``` Dic = {"A": ["od"], "ab": ["od"], "Acutus": ["Akuten", "Akutna", "Akutno"], "Aromaticus": ["Dišeč", "Odišavljen"]} ``` So now after you get the text from your app, let's say it is `text = 'ab:id'`. You will split it to key and value then check in your dict: ``` def check(text): text = text.split(':') key = text[0] value = text[1] if value in Dic[key]: return True return False ``` Let's try it out ``` >>> check('ab:id') False >>> check('ab:od') True >>> check('Acutus:Akutna') True >>> check('Acutus:Akutno') True ```
Do you only need to translate from latin -> slovenian and not the other way around? If so, just make every key a single word. It's OK for multiple keys to have the same value: ```py Dic = { "Aegrotus": "bolnik", "Aether": "eter", "A": "od", "ab": "od", "Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": ("Dišeč", "Odišavljen"), } ``` Each lookup if then of the form `Dic[latin] -> slovenian`, where `latin` is a single word and `slovenian` is one or more words.
61,039,847
I am making Exam app with kivy(python) and I have problem with getting correct answer. I have dictonary of translates from latin words to slovenian words exemple(Keys are latin words, values are slovenian words): ``` Dic = {"Aegrotus": "bolnik", "Aether": "eter"} ``` So the problem is when 2 or 3 latin words mean same as 1 sloveian word and vice versa. Exemple: ``` Dic = {("A", "ab"): "od", "Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": ("Dišeč", "Odišavljen")} ``` For example: [Exemple\_pic](https://i.stack.imgur.com/A8WTz.png) On image you see app, I have to translate "Agito" what means "stresam" So my question is how to check if its multiple keys what is its value. I hope you understand my question :).
2020/04/05
[ "https://Stackoverflow.com/questions/61039847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11590506/" ]
Firstly, you have to be able to get the text output from the app shown in the picture, then you use your dictionary to check it. And the way to design the dictionary makes it difficult to check. You should design it that way: key is only one string, and values is a list. For example: ``` Dic = {"A": ["od"], "ab": ["od"], "Acutus": ["Akuten", "Akutna", "Akutno"], "Aromaticus": ["Dišeč", "Odišavljen"]} ``` So now after you get the text from your app, let's say it is `text = 'ab:id'`. You will split it to key and value then check in your dict: ``` def check(text): text = text.split(':') key = text[0] value = text[1] if value in Dic[key]: return True return False ``` Let's try it out ``` >>> check('ab:id') False >>> check('ab:od') True >>> check('Acutus:Akutna') True >>> check('Acutus:Akutno') True ```
you could use `dict.items()` (`dict.iteritems()` for python2, but why am I even mentioning that ?) so try something like ```py for latin_words, slovenian_words in dic.items(): if isinstance(latin_words, tuple): # this is the check # if there are multiple values # this will run ... if isinstance(slovenian_words, tuple): # this is the check # if there are multiple values # this will run ... ```
61,039,847
I am making Exam app with kivy(python) and I have problem with getting correct answer. I have dictonary of translates from latin words to slovenian words exemple(Keys are latin words, values are slovenian words): ``` Dic = {"Aegrotus": "bolnik", "Aether": "eter"} ``` So the problem is when 2 or 3 latin words mean same as 1 sloveian word and vice versa. Exemple: ``` Dic = {("A", "ab"): "od", "Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": ("Dišeč", "Odišavljen")} ``` For example: [Exemple\_pic](https://i.stack.imgur.com/A8WTz.png) On image you see app, I have to translate "Agito" what means "stresam" So my question is how to check if its multiple keys what is its value. I hope you understand my question :).
2020/04/05
[ "https://Stackoverflow.com/questions/61039847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11590506/" ]
Firstly, you have to be able to get the text output from the app shown in the picture, then you use your dictionary to check it. And the way to design the dictionary makes it difficult to check. You should design it that way: key is only one string, and values is a list. For example: ``` Dic = {"A": ["od"], "ab": ["od"], "Acutus": ["Akuten", "Akutna", "Akutno"], "Aromaticus": ["Dišeč", "Odišavljen"]} ``` So now after you get the text from your app, let's say it is `text = 'ab:id'`. You will split it to key and value then check in your dict: ``` def check(text): text = text.split(':') key = text[0] value = text[1] if value in Dic[key]: return True return False ``` Let's try it out ``` >>> check('ab:id') False >>> check('ab:od') True >>> check('Acutus:Akutna') True >>> check('Acutus:Akutno') True ```
If you want to search both ways, at the trade off of memory usage vs speed of searching, you could consider building a second reversed dictionary. I changed your example to have unique Latin keys in the first dictionary, and then create a second dictionary which has a slightly different structure (can't add to tuples, so sets are used instead), but should be searchable in the same manner as the first. ``` from collections import defaultdict Dic = {"A": "od", "ab": "od", "Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": {"Dišeč", "Odišavljen"}} Dic2 = defaultdict(set) for k, v in Dic.items(): if isinstance(v, str): # just one translation Dic2[v].add(k) else: # more than one translation, given as a tuple for i in v: Dic2[i].add(k) #print(Dic) #print(Dic2) ```
51,187,904
Trying to read a `Parquet` file in PySpark but getting `Py4JJavaError`. I even tried reading it from the `spark-shell` and was able to do so. I cannot understand what I am doing wrong here in terms of the Python APIs that it is working in Scala and not in PySpark; ``` spark = SparkSession.builder.master("local").appName("test-read").getOrCreate() sdf = spark.read.parquet("game_logs.parquet") ``` Stack Trace: ``` Py4JJavaError Traceback (most recent call last) <timed exec> in <module>() ~/pyenv/pyenv/lib/python3.6/site-packages/pyspark/sql/readwriter.py in parquet(self, *paths) 301 [('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')] 302 """ --> 303 return self._df(self._jreader.parquet(_to_seq(self._spark._sc, paths))) 304 305 @ignore_unicode_prefix ~/pyenv/pyenv/lib/python3.6/site-packages/py4j/java_gateway.py in __call__(self, *args) 1255 answer = self.gateway_client.send_command(command) 1256 return_value = get_return_value( -> 1257 answer, self.gateway_client, self.target_id, self.name) 1258 1259 for temp_arg in temp_args: ~/pyenv/pyenv/lib/python3.6/site-packages/pyspark/sql/utils.py in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---> 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() ~/pyenv/pyenv/lib/python3.6/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 326 raise Py4JJavaError( 327 "An error occurred while calling {0}{1}{2}.\n". --> 328 format(target_id, ".", name), value) 329 else: 330 raise Py4JError( Py4JJavaError: An error occurred while calling o26.parquet. : java.lang.IllegalArgumentException at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source) at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source) at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source) at org.apache.spark.util.ClosureCleaner$.getClassReader(ClosureCleaner.scala:46) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:449) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:432) at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:733) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:230) at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:40) at scala.collection.mutable.HashMap$$anon$1.foreach(HashMap.scala:103) at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:732) at org.apache.spark.util.FieldAccessFinder$$anon$3.visitMethodInsn(ClosureCleaner.scala:432) at org.apache.xbean.asm5.ClassReader.a(Unknown Source) at org.apache.xbean.asm5.ClassReader.b(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:262) at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:261) at scala.collection.immutable.List.foreach(List.scala:381) at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:261) at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:159) at org.apache.spark.SparkContext.clean(SparkContext.scala:2299) at org.apache.spark.SparkContext.runJob(SparkContext.scala:2073) at org.apache.spark.SparkContext.runJob(SparkContext.scala:2099) at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:939) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112) at org.apache.spark.rdd.RDD.withScope(RDD.scala:363) at org.apache.spark.rdd.RDD.collect(RDD.scala:938) at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$.mergeSchemasInParallel(ParquetFileFormat.scala:611) at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat.inferSchema(ParquetFileFormat.scala:241) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:202) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:202) at scala.Option.orElse(Option.scala:289) at org.apache.spark.sql.execution.datasources.DataSource.getOrInferFileFormatSchema(DataSource.scala:201) at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:392) at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:239) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:227) at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:622) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:282) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:238) at java.base/java.lang.Thread.run(Thread.java:844 ``` Enviornment Info: ``` Spark version 2.3.1 Using Scala version 2.11.8, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_172 Python 3.6.5 PySpark 2.3.1 ```
2018/07/05
[ "https://Stackoverflow.com/questions/51187904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5129047/" ]
I figured out what was going wrong exactly. The `spark-shell` was using `Java 1.8`, but `PySpark` was using `Java 10.1`. There is some issue with Java 1.9/10 and Spark. Changed the default Java version to 1.8.
Spark runs on Java 8/11. For switching between Java versions, you can add this to your .bashrc/.zshrc file: ```sh alias j='f(){ export JAVA_HOME=$(/usr/libexec/java_home -v $1) };f' ``` Then in your terminal: ```sh source .zshrc ``` ```sh j 1.8 ``` ```sh java -version ``` This will change the version system-wide. If you just want it different for one app you can prepend it with the environment variable JAVA\_HOME ```sh JAVA_HOME=$(/usr/libexec/java_home -v 1.8) jupyter notebook ``` ```py %env JAVA_HOME {path} ```
51,187,904
Trying to read a `Parquet` file in PySpark but getting `Py4JJavaError`. I even tried reading it from the `spark-shell` and was able to do so. I cannot understand what I am doing wrong here in terms of the Python APIs that it is working in Scala and not in PySpark; ``` spark = SparkSession.builder.master("local").appName("test-read").getOrCreate() sdf = spark.read.parquet("game_logs.parquet") ``` Stack Trace: ``` Py4JJavaError Traceback (most recent call last) <timed exec> in <module>() ~/pyenv/pyenv/lib/python3.6/site-packages/pyspark/sql/readwriter.py in parquet(self, *paths) 301 [('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')] 302 """ --> 303 return self._df(self._jreader.parquet(_to_seq(self._spark._sc, paths))) 304 305 @ignore_unicode_prefix ~/pyenv/pyenv/lib/python3.6/site-packages/py4j/java_gateway.py in __call__(self, *args) 1255 answer = self.gateway_client.send_command(command) 1256 return_value = get_return_value( -> 1257 answer, self.gateway_client, self.target_id, self.name) 1258 1259 for temp_arg in temp_args: ~/pyenv/pyenv/lib/python3.6/site-packages/pyspark/sql/utils.py in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---> 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() ~/pyenv/pyenv/lib/python3.6/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 326 raise Py4JJavaError( 327 "An error occurred while calling {0}{1}{2}.\n". --> 328 format(target_id, ".", name), value) 329 else: 330 raise Py4JError( Py4JJavaError: An error occurred while calling o26.parquet. : java.lang.IllegalArgumentException at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source) at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source) at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source) at org.apache.spark.util.ClosureCleaner$.getClassReader(ClosureCleaner.scala:46) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:449) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:432) at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:733) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:230) at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:40) at scala.collection.mutable.HashMap$$anon$1.foreach(HashMap.scala:103) at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:732) at org.apache.spark.util.FieldAccessFinder$$anon$3.visitMethodInsn(ClosureCleaner.scala:432) at org.apache.xbean.asm5.ClassReader.a(Unknown Source) at org.apache.xbean.asm5.ClassReader.b(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:262) at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:261) at scala.collection.immutable.List.foreach(List.scala:381) at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:261) at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:159) at org.apache.spark.SparkContext.clean(SparkContext.scala:2299) at org.apache.spark.SparkContext.runJob(SparkContext.scala:2073) at org.apache.spark.SparkContext.runJob(SparkContext.scala:2099) at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:939) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112) at org.apache.spark.rdd.RDD.withScope(RDD.scala:363) at org.apache.spark.rdd.RDD.collect(RDD.scala:938) at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$.mergeSchemasInParallel(ParquetFileFormat.scala:611) at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat.inferSchema(ParquetFileFormat.scala:241) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:202) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:202) at scala.Option.orElse(Option.scala:289) at org.apache.spark.sql.execution.datasources.DataSource.getOrInferFileFormatSchema(DataSource.scala:201) at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:392) at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:239) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:227) at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:622) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:282) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:238) at java.base/java.lang.Thread.run(Thread.java:844 ``` Enviornment Info: ``` Spark version 2.3.1 Using Scala version 2.11.8, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_172 Python 3.6.5 PySpark 2.3.1 ```
2018/07/05
[ "https://Stackoverflow.com/questions/51187904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5129047/" ]
I figured out what was going wrong exactly. The `spark-shell` was using `Java 1.8`, but `PySpark` was using `Java 10.1`. There is some issue with Java 1.9/10 and Spark. Changed the default Java version to 1.8.
Java Version: openjdk version "1.8.0\_275" OpenJDK Runtime Environment (build 1.8.0\_275-b01) OpenJDK 64-Bit Server VM (build 25.275-b01, mixed mode) Python Version: Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. PySpark Version: 3.0.1 (Note: This version is the key) This combination works fine.
51,187,904
Trying to read a `Parquet` file in PySpark but getting `Py4JJavaError`. I even tried reading it from the `spark-shell` and was able to do so. I cannot understand what I am doing wrong here in terms of the Python APIs that it is working in Scala and not in PySpark; ``` spark = SparkSession.builder.master("local").appName("test-read").getOrCreate() sdf = spark.read.parquet("game_logs.parquet") ``` Stack Trace: ``` Py4JJavaError Traceback (most recent call last) <timed exec> in <module>() ~/pyenv/pyenv/lib/python3.6/site-packages/pyspark/sql/readwriter.py in parquet(self, *paths) 301 [('name', 'string'), ('year', 'int'), ('month', 'int'), ('day', 'int')] 302 """ --> 303 return self._df(self._jreader.parquet(_to_seq(self._spark._sc, paths))) 304 305 @ignore_unicode_prefix ~/pyenv/pyenv/lib/python3.6/site-packages/py4j/java_gateway.py in __call__(self, *args) 1255 answer = self.gateway_client.send_command(command) 1256 return_value = get_return_value( -> 1257 answer, self.gateway_client, self.target_id, self.name) 1258 1259 for temp_arg in temp_args: ~/pyenv/pyenv/lib/python3.6/site-packages/pyspark/sql/utils.py in deco(*a, **kw) 61 def deco(*a, **kw): 62 try: ---> 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: 65 s = e.java_exception.toString() ~/pyenv/pyenv/lib/python3.6/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 326 raise Py4JJavaError( 327 "An error occurred while calling {0}{1}{2}.\n". --> 328 format(target_id, ".", name), value) 329 else: 330 raise Py4JError( Py4JJavaError: An error occurred while calling o26.parquet. : java.lang.IllegalArgumentException at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source) at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source) at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source) at org.apache.spark.util.ClosureCleaner$.getClassReader(ClosureCleaner.scala:46) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:449) at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:432) at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:733) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:103) at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:230) at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:40) at scala.collection.mutable.HashMap$$anon$1.foreach(HashMap.scala:103) at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:732) at org.apache.spark.util.FieldAccessFinder$$anon$3.visitMethodInsn(ClosureCleaner.scala:432) at org.apache.xbean.asm5.ClassReader.a(Unknown Source) at org.apache.xbean.asm5.ClassReader.b(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.xbean.asm5.ClassReader.accept(Unknown Source) at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:262) at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:261) at scala.collection.immutable.List.foreach(List.scala:381) at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:261) at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:159) at org.apache.spark.SparkContext.clean(SparkContext.scala:2299) at org.apache.spark.SparkContext.runJob(SparkContext.scala:2073) at org.apache.spark.SparkContext.runJob(SparkContext.scala:2099) at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:939) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112) at org.apache.spark.rdd.RDD.withScope(RDD.scala:363) at org.apache.spark.rdd.RDD.collect(RDD.scala:938) at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$.mergeSchemasInParallel(ParquetFileFormat.scala:611) at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat.inferSchema(ParquetFileFormat.scala:241) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:202) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$8.apply(DataSource.scala:202) at scala.Option.orElse(Option.scala:289) at org.apache.spark.sql.execution.datasources.DataSource.getOrInferFileFormatSchema(DataSource.scala:201) at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:392) at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:239) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:227) at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:622) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:282) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:238) at java.base/java.lang.Thread.run(Thread.java:844 ``` Enviornment Info: ``` Spark version 2.3.1 Using Scala version 2.11.8, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_172 Python 3.6.5 PySpark 2.3.1 ```
2018/07/05
[ "https://Stackoverflow.com/questions/51187904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5129047/" ]
Spark runs on Java 8/11. For switching between Java versions, you can add this to your .bashrc/.zshrc file: ```sh alias j='f(){ export JAVA_HOME=$(/usr/libexec/java_home -v $1) };f' ``` Then in your terminal: ```sh source .zshrc ``` ```sh j 1.8 ``` ```sh java -version ``` This will change the version system-wide. If you just want it different for one app you can prepend it with the environment variable JAVA\_HOME ```sh JAVA_HOME=$(/usr/libexec/java_home -v 1.8) jupyter notebook ``` ```py %env JAVA_HOME {path} ```
Java Version: openjdk version "1.8.0\_275" OpenJDK Runtime Environment (build 1.8.0\_275-b01) OpenJDK 64-Bit Server VM (build 25.275-b01, mixed mode) Python Version: Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. PySpark Version: 3.0.1 (Note: This version is the key) This combination works fine.
5,838,307
I'd like to create a drop-in replacement for python's `list`, that will allow me to know when an item is added or removed. A subclass of list, or something that implements the list interface will do equally well. I'd prefer a solution where I don't have to reimplement all of list's functionality though. Is there a easy + pythonic way to do it? Pseudocode: ``` class MyList(list): # ... def on_add(self, items): print "Added:" for i in items: print i # and the same for on_remove l = MyList() l += [1,2,3] # etc. ```
2011/04/29
[ "https://Stackoverflow.com/questions/5838307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143091/" ]
To see what functions are defined in list, you can do ``` >>> dir(list) ``` Then you will see what you can override, try for instance this: ``` class MyList(list): def __iadd__(self, *arg, **kwargs): print "Adding" return list.__iadd__(self, *arg, **kwargs) ``` You probably need to do a few more of them to get all of it.
The [documentation for userlist](http://docs.python.org/release/2.5.2/lib/module-UserList.html) tells you to subclass `list` if you don't require your code to work with Python <2.2. You probably don't get around overriding at least the methods which allow to add/remove elements. Beware, this includes the slicing operators.
18,619,205
To start I will mention that I am new to the Python Language and come from a networking background. If you are wondering why I am using Python 2.5 it is due to some device constraints. What I am trying to do is count the number of lines that are in a string of data as seen below. (not in a file) ``` data = ['This','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\n'] ``` Unfortunately I can't seem to get the correct syntax to count **\n**. So far this is what I have come up with. ``` num = data.count('\n') print num ``` The above code is clearly wrong for the intended output since it returns 1 in relation to the test data, I would like to see it return 4 if possible. It only finds 1 of the '\n' being the last one in the example since it matches. If I use the following code instead to find all of them it doesn't run due to syntax. ``` num = data.count (\n) print num ``` I based this code from the following link, the example is the third one down. <http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/strings3.html> Is there anyway of accomplishing this or should I be looking at a different solution? Any help is appreciated Thank-you
2013/09/04
[ "https://Stackoverflow.com/questions/18619205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2240963/" ]
`list.count` is used to get the count of an item in list, but you need to do a substring search in each item to get the count as 4. ``` >>> data = ['This','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\n'] ``` Total number of items that contain `'\n'`: ``` >>> sum('\n' in item for item in data) 4 ``` Sum of count of all `'\n'`s in `data`: ``` >>> data = ['\n\nfoo','\n\n\nbar'] >>> sum(item.count('\n') for item in data) 5 ```
Your first code does not work because you only have one `'\n'` in your actual list of strings. When you compare `'\n'` to something like `'nThis'`, then it will say that `\n` is not equal to that string and not include it in the count. What you can do is join the list into a string like so: ``` x = ''.join(num) ``` and then try using the `count` method of the string class. This will let you find substrings that are equivalent to '\n' in the total string. ``` y = x.count('\n') print y ```
54,997,210
Im currently writing a program in python where I have to figure out smileys like these `:)`, `:(`, `:-)`, `:-(` should be replace if it is followed by special characters and punctuation should be replaced in this pattern : ex : `Hi, this is good :)#` should be replaced to `Hi, this is good :)`. I have created regex pattern for sub it but couldn't enclose this smiley `:-)` in my `re.compile`.It is considering that as a range. `re.sub(r"[^a-zA-Z0-9:):D)]+", " " , words)` this is working fine I need to add `:-)` smiley to the regex.
2019/03/05
[ "https://Stackoverflow.com/questions/54997210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4045224/" ]
One approach is to use the following pattern: ``` (:\)|:\(|:-\)|:-\()[^A-Za-z0-9]+ ``` This matches *and* captures a smiley face, then matches any number of non alphanumeric characters immediately afterwards. The replacement is just the captured smiley face, thereby removing the non alpha characters. ``` input = "Hi, this is good :)#" output = re.sub(r"(:\)|:\(|:-\)|:-\()[^A-Za-z0-9]+", "\1" , input) print(output) Hi, this is good :) ```
you can escape special characters with `\` try: ``` re.sub("[^a-zA-Z0-9:):D:\-))]+", " " , words) ```
54,997,210
Im currently writing a program in python where I have to figure out smileys like these `:)`, `:(`, `:-)`, `:-(` should be replace if it is followed by special characters and punctuation should be replaced in this pattern : ex : `Hi, this is good :)#` should be replaced to `Hi, this is good :)`. I have created regex pattern for sub it but couldn't enclose this smiley `:-)` in my `re.compile`.It is considering that as a range. `re.sub(r"[^a-zA-Z0-9:):D)]+", " " , words)` this is working fine I need to add `:-)` smiley to the regex.
2019/03/05
[ "https://Stackoverflow.com/questions/54997210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4045224/" ]
The `[^a-zA-Z0-9:):D)]` pattern is erronrous since it is a character class meant to match sequences of chars. You need to add an alternative to this regex that will match char sequences. To remove any punctuation other than a certain list of smileys you may use ``` re.sub(r"(:-?[()D])|[^A-Za-z0-9\s]", r"\1" , s) ``` Or, in Python 3.4 and older, due to [the `re.sub` bug](https://stackoverflow.com/a/35516425/3832970): ``` re.sub(r"(:-?[()D])|[^A-Za-z0-9,\s]", lambda x: x.group(1) if x.group(1) else "", s) ``` If you really need to avoid removing commas, add `,` into the negated character class: ``` re.sub(r"(:-?[()D])|[^A-Za-z0-9,\s]", r"\1" , s) ^ ``` See the [regex demo](https://regex101.com/r/nDN665/1). **Details** * `(:-?[()D])` - matches and captures into Group 1 a `:`, then an optional `-`, and then a single char from the character class: `(`, `)` or `D` (this captures the smileys like `:-)`, `:-(`, `:)`, `:(`, `:-D`, `:D`) * `[^A-Za-z0-9,\s]` - matches any char but an ASCII letter, digit, comma and whitespace. To make it fully Unicode aware, replace with `(?:[^\w\s,]|_)`. See the [Python 3.5+ demo](https://ideone.com/kjTKsR): ``` import re s = "Hi, this is good :)#" print( re.sub(r"(:-?[()D])|[^A-Za-z0-9,\s]", r"\1" , s) ) # => Hi, this is good :) ``` See [this Python 3.4- demo](https://stackoverflow.com/a/35516425/3832970): ``` import re s = "Hi, this is good :)#" print( re.sub(r"(:-?[()D])|[^A-Za-z0-9,\s]", lambda x: x.group(1) if x.group(1) else "", s) ) # => Hi, this is good :) ```
you can escape special characters with `\` try: ``` re.sub("[^a-zA-Z0-9:):D:\-))]+", " " , words) ```
37,451,031
I have some python code to unzip a file and then remove it (the original file), but my code catches an exception: it cannot remove the file, because it is in use. I think the problem is that when the removal code runs, the unzip action has not finished, so the exception is thrown. So, how can I check the run state of the unzip action before removing the file? ``` file = zipfile.ZipFile(lfilename) for filename in file.namelist(): file.extract(filename,dir) remove(lfilename) ```
2016/05/26
[ "https://Stackoverflow.com/questions/37451031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213922/" ]
The documentation for ZipFile says: > > ZipFile is also a context manager and therefore supports the [with](https://docs.python.org/2/reference/compound_stmts.html#with) statement. > > > So, I'd recommend doing the following: ``` with zipfile.ZipFile(lfilename) as file: file.extract(filename, dir) remove(lfilename) ``` One advantage of using a with statement is that the file is closed automatically. It is also beautiful (short, concise, effective). See also [PEP 343](https://www.python.org/dev/peps/pep-0343/).
Try closing the file before removing it. ``` file = zipfile.ZipFile(lfilename) for filename in file.namelist(): file.extract(filename,dir) file.close() remove(lfilename) ```
37,451,031
I have some python code to unzip a file and then remove it (the original file), but my code catches an exception: it cannot remove the file, because it is in use. I think the problem is that when the removal code runs, the unzip action has not finished, so the exception is thrown. So, how can I check the run state of the unzip action before removing the file? ``` file = zipfile.ZipFile(lfilename) for filename in file.namelist(): file.extract(filename,dir) remove(lfilename) ```
2016/05/26
[ "https://Stackoverflow.com/questions/37451031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213922/" ]
Try closing the file before removing it. ``` file = zipfile.ZipFile(lfilename) for filename in file.namelist(): file.extract(filename,dir) file.close() remove(lfilename) ```
You must first close the file. ``` file.close() remove(lfilename) ``` Alternatively you could do the following: ``` with ZipFile('lfilename') as file: for filename in file.namelist(): file.extract(filename,dir) remove(lfilename) ```
37,451,031
I have some python code to unzip a file and then remove it (the original file), but my code catches an exception: it cannot remove the file, because it is in use. I think the problem is that when the removal code runs, the unzip action has not finished, so the exception is thrown. So, how can I check the run state of the unzip action before removing the file? ``` file = zipfile.ZipFile(lfilename) for filename in file.namelist(): file.extract(filename,dir) remove(lfilename) ```
2016/05/26
[ "https://Stackoverflow.com/questions/37451031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213922/" ]
The documentation for ZipFile says: > > ZipFile is also a context manager and therefore supports the [with](https://docs.python.org/2/reference/compound_stmts.html#with) statement. > > > So, I'd recommend doing the following: ``` with zipfile.ZipFile(lfilename) as file: file.extract(filename, dir) remove(lfilename) ``` One advantage of using a with statement is that the file is closed automatically. It is also beautiful (short, concise, effective). See also [PEP 343](https://www.python.org/dev/peps/pep-0343/).
You must first close the file. ``` file.close() remove(lfilename) ``` Alternatively you could do the following: ``` with ZipFile('lfilename') as file: for filename in file.namelist(): file.extract(filename,dir) remove(lfilename) ```
33,687,594
I have been trying to debug this issue, but can't seem to figure it out. When debugging I can see that all the variables are where they should be, but I can't seem to get them out. When running I get the error message `'dict' object is not callable` This is the full error message from Django ``` Environment: Request Method: GET Request URL: http://127.0.0.1:8000/?form_base_currency=7&form_counter_currency=14&form_base_amount=127 Django Version: 1.8.6 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'client'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/johan/sdp/currency-converter/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/johan/sdp/currency-converter/currency_converter/client/views.py" in index 22. form_base_currency = form.cleaned_data('form_base_currency').currency_code Exception Type: TypeError at / Exception Value: 'dict' object is not callable ``` For clarity I have added a screenshot from the debugger variables. [![enter image description here](https://i.stack.imgur.com/YxCha.png)](https://i.stack.imgur.com/YxCha.png) This is the code I have been using: ``` if request.method == 'GET': form = CurrencyConverterForm(request.GET) if form.is_valid(): form_base_currency = form.cleaned_data('form_base_currency').currency_code form_counter_currency = form.cleaned_data('form_counter_currency') form_base_amount = form.data.cleaned_data('form_base_amount') ``` To get form\_base\_currency working I tried these different methods: ``` form_base_currency = form.cleaned_data('form_base_currency').currency_code form_base_currency = form.cleaned_data.form_base_currency.currency_code form_base_currency = form.cleaned_data('form_base_currency.currency_code') ``` None of them work. Could someone tell me how I can solve this?
2015/11/13
[ "https://Stackoverflow.com/questions/33687594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5039579/" ]
Dictionaries need square brackets ``` form_counter_currency = form.cleaned_data['form_counter_currency'] ``` although you may want to use `get` so you can provide a default ``` form_counter_currency = form.cleaned_data.get('form_counter_currency', None) ```
import this ``` from rest_framework.response import Response ``` Then after write this in **views.py** file ``` class userlist(APIView): def get(self,request): user1=webdata.objects.all() serializer=webdataserializers(user1,many=True) return Response(serializer.data) def post(self): pass ```
7,748,563
*Disclaimer: complete rewrite for clarity as of 10/14/2011* **Given** the `number` primitive in JavaScript is an [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754-2008) 64-bit floating point (*known in other languages as a double*), and [using floats to model currencies is a **bad idea**](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency), **is a Money prototype** (JavaScript) **or a [Coffeescript Class](http://rzrsharp.net/2011/06/21/classes-in-coffeescript.html)** that eases use of pseudo-integer cents and string [currency ISO 4217 code](http://en.wikipedia.org/wiki/ISO_4217) to represent currency **available**? ^ There's still gotta be a better way to say that. I'm hoping to find something that mirrors the common design pattern of the many other languages out there that do include an integer primitive. As examples, I'm familiar with the [money gem](http://rubygems.org/gems/money) for ruby, and the [python-money](http://pypi.python.org/pypi/python-money/0.5) package, both of which implement variations of this design pattern. Ideally looking for something that will play nice with [backbone.js](http://documentcloud.github.com/backbone/) and [node.js](http://nodejs.org/), but all suggestions appreciated. *Edit 4*: As far as I can tell, as long as an implementation of `roundDownOrUp ? floor : ceiling` is called on the Number after every operation (& in between chained operations) everything would function as if one were dealing with integers. --- ### Old information, retained to document the history of the question. I read [How can I format numbers as money in JavaScript?](https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) where I found [accounting.js](http://josscrowcroft.github.com/accounting.js/) and [jQuery Globalize](http://wiki.jqueryui.com/w/page/39118647/Globalize) which both do pretty printing but are not designed to model currencies and perform operations with them. *Edit 1*: Just found [JSorm Currency](http://jsorm.com/wiki/Currency) in the [npm registry](http://search.npmjs.org/#/jsorm-i18n) which is ISO 4217 aware, but does not appear to include any fixes for float "*gotchas*". Please correct if I have misread. *Edit 2 folded into rewrite.* *Edit 3*: It looks like a good option would be to use [node-bigint](https://github.com/substack/node-bigint) as suggested by @RicardoTomasi.
2011/10/13
[ "https://Stackoverflow.com/questions/7748563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902839/" ]
Both [bigdecimal.js](https://github.com/jhs/bigdecimal.js/) and [node-bigint](https://github.com/substack/node-bigint) have arbitrary precision. I'd go with bigint. bigdecimal is a GWT version of of Java's BigDecimal, clocking in at 113kb, so the code is not what one would call *readable*. **update:** [money.js](http://josscrowcroft.github.com/money.js/) has just been released, but it uses javascript's native Number, and is focused on currency conversion.
There is a GREAT $.money class the does almost everything you could ever want from money in the ku4js-kernel library. You can find the documentation [here](http://kodmunki.github.io/ku4js-kernel/#money). Have fun! :{)}
7,748,563
*Disclaimer: complete rewrite for clarity as of 10/14/2011* **Given** the `number` primitive in JavaScript is an [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754-2008) 64-bit floating point (*known in other languages as a double*), and [using floats to model currencies is a **bad idea**](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency), **is a Money prototype** (JavaScript) **or a [Coffeescript Class](http://rzrsharp.net/2011/06/21/classes-in-coffeescript.html)** that eases use of pseudo-integer cents and string [currency ISO 4217 code](http://en.wikipedia.org/wiki/ISO_4217) to represent currency **available**? ^ There's still gotta be a better way to say that. I'm hoping to find something that mirrors the common design pattern of the many other languages out there that do include an integer primitive. As examples, I'm familiar with the [money gem](http://rubygems.org/gems/money) for ruby, and the [python-money](http://pypi.python.org/pypi/python-money/0.5) package, both of which implement variations of this design pattern. Ideally looking for something that will play nice with [backbone.js](http://documentcloud.github.com/backbone/) and [node.js](http://nodejs.org/), but all suggestions appreciated. *Edit 4*: As far as I can tell, as long as an implementation of `roundDownOrUp ? floor : ceiling` is called on the Number after every operation (& in between chained operations) everything would function as if one were dealing with integers. --- ### Old information, retained to document the history of the question. I read [How can I format numbers as money in JavaScript?](https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) where I found [accounting.js](http://josscrowcroft.github.com/accounting.js/) and [jQuery Globalize](http://wiki.jqueryui.com/w/page/39118647/Globalize) which both do pretty printing but are not designed to model currencies and perform operations with them. *Edit 1*: Just found [JSorm Currency](http://jsorm.com/wiki/Currency) in the [npm registry](http://search.npmjs.org/#/jsorm-i18n) which is ISO 4217 aware, but does not appear to include any fixes for float "*gotchas*". Please correct if I have misread. *Edit 2 folded into rewrite.* *Edit 3*: It looks like a good option would be to use [node-bigint](https://github.com/substack/node-bigint) as suggested by @RicardoTomasi.
2011/10/13
[ "https://Stackoverflow.com/questions/7748563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902839/" ]
Both [bigdecimal.js](https://github.com/jhs/bigdecimal.js/) and [node-bigint](https://github.com/substack/node-bigint) have arbitrary precision. I'd go with bigint. bigdecimal is a GWT version of of Java's BigDecimal, clocking in at 113kb, so the code is not what one would call *readable*. **update:** [money.js](http://josscrowcroft.github.com/money.js/) has just been released, but it uses javascript's native Number, and is focused on currency conversion.
Was looking for something to handle money in node.js and came across this question, and then found esmoney which is a straightforward money calculator. <https://www.npmjs.com/package/es-money>
67,579,796
I am trying to change the JSON format using python. The received message has some key-value pairs and needs to change certain key names before forwarding the message. for normal key-value pairs, I have used "data. pop" method, data["newkey"]=data.pop("oldkey") . But it got complicated with nested key-values. This is just a part of big file that needs to be convrted. How to convert this ``` { "atrk1": "form_varient", "atrv1": "red_top", "atrt1": "string", "atrk2": "ref", "atrv2": "XPOWJRICW993LKJD", "atrt2": "string" } ``` into this? ``` "attributes": { "form_varient": { "value": "red_top", "type": "string" }, "ref": { "value": "XPOWJRICW993LKJD", "type": "string" } } ``` ---
2021/05/18
[ "https://Stackoverflow.com/questions/67579796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15715705/" ]
If the keys gonna be in the same format you can do something like this. ``` d = { "ev": "contact_form_submitted", "et": "form_submit", "id": "cl_app_id_001", "uid": "cl_app_id_001-uid-001", "mid": "cl_app_id_001-uid-001", "t": "Vegefoods - Free Bootstrap 4 Template by Colorlib", "p": "http://shielded-eyrie-45679.herokuapp.com/contact-us", "l": "en-US", "sc": "1920 x 1080", "atrk1": "form_varient", "atrv1": "red_top", "atrt1": "string", "atrk2": "ref", "atrv2": "XPOWJRICW993LKJD", "atrt2": "string", "uatrk1": "name", "uatrv1": "iron man", "uatrt1": "string", "uatrk2": "email", "uatrv2": "ironman@avengers.com", "uatrt2": "string", "uatrk3": "age", "uatrv3": "32", "uatrt3": "integer" } d["attributes"] = {} d["traits"] = {} keys_to_remove = [] for k in d.keys(): if k.startswith("atrk"): value_key = k.replace("atrk","atrv") type_key = k.replace("atrk","atrt") d["attributes"][d[k]] = {"value":d[value_key],"type":d[type_key]} keys_to_remove += [value_key,k,type_key] if k.startswith("uatrk"): keys_to_remove.append(k) value_key = k.replace("uatrk","uatrv") type_key = k.replace("uatrk","uatrt") d["traits"][d[k]] = {"value":d[value_key],"type":d[type_key]} keys_to_remove += [value_key,k,type_key] for k in keys_to_remove: if k in d: del d[k] ```
Use the following code it will successfully convert it. ``` json1={ "atrk1": "form_varient", "atrv1": "red_top", "atrt1": "string", "atrk2": "ref", "atrv2": "XPOWJRICW993LKJD", "atrt2": "string" } json2={} keys=[] values=[] types=[] for i in json1: if i[:4]=='atrk': keys.append(json1[i]) values.append([]) types.append([]) elif i[:4]=='atrv': values[int(i[-1:])-1].append(json1[i]) elif i[:4]=='atrt': types[int(i[-1:])-1].append(json1[i]) for i in range(len(keys)): json2[keys[i]]={ 'value':values[i],'type':types[i] } json3={} json3['attributes']=json2 print(json3) ```
58,740,865
I'm trying to scrape this page/iframe with selenium/python but I can't insert any text in this selected form. [link](https://ibb.co/cF8ZRZP) ```py from selenium import webdriver from time import sleep driver = webdriver.Firefox() url = 'http://web.transparencia.pe.gov.br/despesas/despesa-geral/' driver.get(url) sleep(10) driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) el = driver.find_element_by_xpath("//*[@id='html_selectug']") el.click() ``` When I try to get the listbox: ``` el_cl = el.find_element_by_class_name('chzn-select') el_cl.click() ``` An exception is raised ``` selenium.common.exceptions.ElementNotInteractableException: Message: Element <select class="chzn-select"> could not be scrolled into view ``` any tips?
2019/11/07
[ "https://Stackoverflow.com/questions/58740865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7651009/" ]
In such kind of situation, the right tool is to use [std::integer\_sequence](https://en.cppreference.com/w/cpp/utility/integer_sequence) ``` #include <iostream> #include <utility> template <size_t N> void make() { std::cout << N << std::endl; } template <size_t... I> void do_make_helper(std::index_sequence<I...>) { (make<I+1>(), ...); } template <std::size_t N> void do_make() { do_make_helper(std::make_index_sequence<N>()); } int main() { do_make<10>(); } ``` prints ``` 1 2 3 4 5 6 7 8 9 10 ```
As a start point with handcrafted index list: ``` template <size_t N> int make(); template<> int make<1>() { std::cout<< "First" << std::endl; return 100; } template<> int make<2>() { std::cout << "Second" << std::endl; return 200; } template<> int make<3>() { std::cout << "Third" << std::endl; return 100; } struct ExecuteInOrder { ExecuteInOrder( ... ) {} }; template < typename T> void CallTest(T t ) { std::cout << "Your test code goes here...: " << t << std::endl; } template< size_t ... N > void Do() { ExecuteInOrder {(CallTest(make<N>()),1)...}; } int main() { Do<1,2,3>(); } ``` or you can simply make it recursive and use index first and last like this: ``` template < size_t FIRST, size_t LAST > void ExecuteAndTest() { auto foo = make<FIRST>(); std::cout << "Here we go with the test" << foo << std::endl; // go for next step if constexpr ( LAST != FIRST ) { ExecuteAndTest<FIRST+1, LAST>(); } } int main() { // first and last index of integer sequence ExecuteAndTest<1,3>(); } ``` and finally with always from 1 to N ``` template < size_t FIRST, size_t LAST > void ExecuteAndTest_Impl() { auto foo = make<FIRST>(); std::cout << "Here we go with the test" << foo << std::endl; // go for next step if constexpr ( LAST!= FIRST) { ExecuteAndTest_Impl<FIRST+1, LAST>(); } } template < size_t LAST > void ExecuteAndTest() { ExecuteAndTest_Impl<1,LAST>(); } int main() { // or always start with 1 to n inclusive ExecuteAndTest<3>(); } ```
58,740,865
I'm trying to scrape this page/iframe with selenium/python but I can't insert any text in this selected form. [link](https://ibb.co/cF8ZRZP) ```py from selenium import webdriver from time import sleep driver = webdriver.Firefox() url = 'http://web.transparencia.pe.gov.br/despesas/despesa-geral/' driver.get(url) sleep(10) driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) el = driver.find_element_by_xpath("//*[@id='html_selectug']") el.click() ``` When I try to get the listbox: ``` el_cl = el.find_element_by_class_name('chzn-select') el_cl.click() ``` An exception is raised ``` selenium.common.exceptions.ElementNotInteractableException: Message: Element <select class="chzn-select"> could not be scrolled into view ``` any tips?
2019/11/07
[ "https://Stackoverflow.com/questions/58740865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7651009/" ]
As a start point with handcrafted index list: ``` template <size_t N> int make(); template<> int make<1>() { std::cout<< "First" << std::endl; return 100; } template<> int make<2>() { std::cout << "Second" << std::endl; return 200; } template<> int make<3>() { std::cout << "Third" << std::endl; return 100; } struct ExecuteInOrder { ExecuteInOrder( ... ) {} }; template < typename T> void CallTest(T t ) { std::cout << "Your test code goes here...: " << t << std::endl; } template< size_t ... N > void Do() { ExecuteInOrder {(CallTest(make<N>()),1)...}; } int main() { Do<1,2,3>(); } ``` or you can simply make it recursive and use index first and last like this: ``` template < size_t FIRST, size_t LAST > void ExecuteAndTest() { auto foo = make<FIRST>(); std::cout << "Here we go with the test" << foo << std::endl; // go for next step if constexpr ( LAST != FIRST ) { ExecuteAndTest<FIRST+1, LAST>(); } } int main() { // first and last index of integer sequence ExecuteAndTest<1,3>(); } ``` and finally with always from 1 to N ``` template < size_t FIRST, size_t LAST > void ExecuteAndTest_Impl() { auto foo = make<FIRST>(); std::cout << "Here we go with the test" << foo << std::endl; // go for next step if constexpr ( LAST!= FIRST) { ExecuteAndTest_Impl<FIRST+1, LAST>(); } } template < size_t LAST > void ExecuteAndTest() { ExecuteAndTest_Impl<1,LAST>(); } int main() { // or always start with 1 to n inclusive ExecuteAndTest<3>(); } ```
You can try this: ``` #include <utility> #include <cassert> struct Foo { Foo() {} Foo(std::size_t i) : i(i) {} std::size_t i; }; template <std::size_t... Is> void setFoo(std::size_t i, Foo& foo, std::index_sequence<Is...>) { ((i == Is && (foo = Foo{Is}, false)), ...); } int main() { for (std::size_t i = 0; i < 10; i++) { Foo foo; setFoo(i, foo, std::make_index_sequence<10>{}); assert(foo.i == i); } } ```
58,740,865
I'm trying to scrape this page/iframe with selenium/python but I can't insert any text in this selected form. [link](https://ibb.co/cF8ZRZP) ```py from selenium import webdriver from time import sleep driver = webdriver.Firefox() url = 'http://web.transparencia.pe.gov.br/despesas/despesa-geral/' driver.get(url) sleep(10) driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) el = driver.find_element_by_xpath("//*[@id='html_selectug']") el.click() ``` When I try to get the listbox: ``` el_cl = el.find_element_by_class_name('chzn-select') el_cl.click() ``` An exception is raised ``` selenium.common.exceptions.ElementNotInteractableException: Message: Element <select class="chzn-select"> could not be scrolled into view ``` any tips?
2019/11/07
[ "https://Stackoverflow.com/questions/58740865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7651009/" ]
In such kind of situation, the right tool is to use [std::integer\_sequence](https://en.cppreference.com/w/cpp/utility/integer_sequence) ``` #include <iostream> #include <utility> template <size_t N> void make() { std::cout << N << std::endl; } template <size_t... I> void do_make_helper(std::index_sequence<I...>) { (make<I+1>(), ...); } template <std::size_t N> void do_make() { do_make_helper(std::make_index_sequence<N>()); } int main() { do_make<10>(); } ``` prints ``` 1 2 3 4 5 6 7 8 9 10 ```
You can try this: ``` #include <utility> #include <cassert> struct Foo { Foo() {} Foo(std::size_t i) : i(i) {} std::size_t i; }; template <std::size_t... Is> void setFoo(std::size_t i, Foo& foo, std::index_sequence<Is...>) { ((i == Is && (foo = Foo{Is}, false)), ...); } int main() { for (std::size_t i = 0; i < 10; i++) { Foo foo; setFoo(i, foo, std::make_index_sequence<10>{}); assert(foo.i == i); } } ```
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.com/questions/3357581/using-python-class-as-a-data-container/)” where @joe-kington had a good point to use built-in `namedtuple`. **Question** In section 8.3.4 of python 2.7 documentation there is good [example](https://docs.python.org/2.7/library/collections.html#collections.somenamedtuple._fields) on how to combine several named tuples. My question is how to achieve the reverse? **Example** Considering the example from documentation: ``` >>> p._fields # view the field names ('x', 'y') >>> Color = namedtuple('Color', 'red green blue') >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0) ``` How can I deduce a “Color” or a “Point” instance from a “Pixel” instance? Preferably in *pythonic* spirit.
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here it is. By the way, if you need this operation often, you may create a function for `color_ins` creation, based on `pixel_ins`. Or even for any subnamedtuple! ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) pixel_ins = Pixel(x=11, y=22, red=128, green=255, blue=0) color_ins = Color._make(getattr(pixel_ins, field) for field in Color._fields) print color_ins ``` Output: `Color(red=128, green=255, blue=0)` Function for extracting arbitrary subnamedtuple (without error handling): ``` def extract_sub_namedtuple(parent_ins, child_cls): return child_cls._make(getattr(parent_ins, field) for field in child_cls._fields) color_ins = extract_sub_namedtuple(pixel_ins, Color) point_ins = extract_sub_namedtuple(pixel_ins, Point) ```
`Point._fields + Color._fields` is simply a tuple. So given this: ``` from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) f = Point._fields + Color._fields ``` `type(f)` is just `tuple`. Therefore, there is no way to know where it came from. I recommend that you look into [attrs](https://attrs.readthedocs.io/en/stable/) for easily doing property objects. This will allow you to do proper inheritance and avoid the overheads of defining all the nice methods to access fields. So you can do ``` import attr @attr.s class Point: x, y = attr.ib(), attr.ib() @attr.s class Color: red, green, blue = attr.ib(), attr.ib(), attr.ib() class Pixel(Point, Color): pass ``` Now, `Pixel.__bases__` will give you `(__main__.Point, __main__.Color)`.
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.com/questions/3357581/using-python-class-as-a-data-container/)” where @joe-kington had a good point to use built-in `namedtuple`. **Question** In section 8.3.4 of python 2.7 documentation there is good [example](https://docs.python.org/2.7/library/collections.html#collections.somenamedtuple._fields) on how to combine several named tuples. My question is how to achieve the reverse? **Example** Considering the example from documentation: ``` >>> p._fields # view the field names ('x', 'y') >>> Color = namedtuple('Color', 'red green blue') >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0) ``` How can I deduce a “Color” or a “Point” instance from a “Pixel” instance? Preferably in *pythonic* spirit.
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
`Point._fields + Color._fields` is simply a tuple. So given this: ``` from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) f = Point._fields + Color._fields ``` `type(f)` is just `tuple`. Therefore, there is no way to know where it came from. I recommend that you look into [attrs](https://attrs.readthedocs.io/en/stable/) for easily doing property objects. This will allow you to do proper inheritance and avoid the overheads of defining all the nice methods to access fields. So you can do ``` import attr @attr.s class Point: x, y = attr.ib(), attr.ib() @attr.s class Color: red, green, blue = attr.ib(), attr.ib(), attr.ib() class Pixel(Point, Color): pass ``` Now, `Pixel.__bases__` will give you `(__main__.Point, __main__.Color)`.
Another way you could do this is to make the arguments for "Pixel" align with what you actually want instead of flattening all of the arguments for its constituent parts. Instead of combining `Point._fields + Color._fields` to get the fields for Pixel, I think you should just have two parameters: `location` and `color`. These two fields could be initialized with your other tuples and you wouldn't have to do any inference. For example: ```py # Instead of Pixel(x=11, y=22, red=128, green=255, blue=0) pixel_ins = Pixel(Point(x=11, y=22), Color(red=128, green=255, blue=0)) # Get the named tuples that the pixel is parameterized by pixel_color = pixel_ins.color pixel_point = pixel_ins.location ``` By mashing all the parameters together (e.g. x, y, red, green, and blue all on the main object) you don't really gain anything, but you lose a lot of legibility. Flattening the parameters also introduces a bug if your namedtuple parameters share fields: ```py from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Hue = namedtuple('Hue', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields + Hue._fields) # Results in: # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # File "C:\Program Files\Python38\lib\collections\__init__.py", line 370, in namedtuple # raise ValueError(f'Encountered duplicate field name: {name!r}') # ValueError: Encountered duplicate field name: 'red' ```
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.com/questions/3357581/using-python-class-as-a-data-container/)” where @joe-kington had a good point to use built-in `namedtuple`. **Question** In section 8.3.4 of python 2.7 documentation there is good [example](https://docs.python.org/2.7/library/collections.html#collections.somenamedtuple._fields) on how to combine several named tuples. My question is how to achieve the reverse? **Example** Considering the example from documentation: ``` >>> p._fields # view the field names ('x', 'y') >>> Color = namedtuple('Color', 'red green blue') >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0) ``` How can I deduce a “Color” or a “Point” instance from a “Pixel” instance? Preferably in *pythonic* spirit.
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
`Point._fields + Color._fields` is simply a tuple. So given this: ``` from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) f = Point._fields + Color._fields ``` `type(f)` is just `tuple`. Therefore, there is no way to know where it came from. I recommend that you look into [attrs](https://attrs.readthedocs.io/en/stable/) for easily doing property objects. This will allow you to do proper inheritance and avoid the overheads of defining all the nice methods to access fields. So you can do ``` import attr @attr.s class Point: x, y = attr.ib(), attr.ib() @attr.s class Color: red, green, blue = attr.ib(), attr.ib(), attr.ib() class Pixel(Point, Color): pass ``` Now, `Pixel.__bases__` will give you `(__main__.Point, __main__.Color)`.
**Background** Originally I've asked this question because I had to support some spaghetti codebase that used tuples a lot but not giving any explanation about the values inside them. After some refactoring, I noticed that I need to extract some typed information from other tuples and was looking for some boilerplate free and type-safe way of doing it. **Solution** You can subclass named tuple definition and implement a custom `__new__` method to support that, optionally carrying out some data formatting and validation on the way. See this [reference](https://jfine-python-classes.readthedocs.io/en/latest/subclass-tuple.html#) for more details. **Example** ```py from __future__ import annotations from collections import namedtuple from typing import Union, Tuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) # Redeclare "Color" to provide custom creation method # that can deduce values from various different types class Color(Color): def __new__(cls, *subject: Union[Pixel, Color, Tuple[float, float, float]]) -> Color: # If got only one argument either of type "Pixel" or "Color" if len(subject) == 1 and isinstance((it := subject[0]), (Pixel, Color)): # Create from invalidated color properties return super().__new__(cls, *cls.invalidate(it.red, it.green, it.blue)) else: # Else treat it as raw values and by-pass them after invalidation return super().__new__(cls, *cls.invalidate(*subject)) @classmethod def invalidate(cls, r, g, b) -> Tuple[float, float, float]: # Convert values to float r, g, b = (float(it) for it in (r, g, b)) # Ensure that all values are in valid range assert all(0 <= it <= 1.0 for it in (r, g, b)), 'Some RGB values are invalid' return r, g, b ``` Now you can instantiate `Color` from any of the supported value types (`Color`, `Pixel`, a triplet of numbers) without boilerplate. ```py color = Color(0, 0.5, 1) from_color = Color(color) from_pixel = Color(Pixel(3.4, 5.6, 0, 0.5, 1)) ``` And you can verify all are equal values: ```py >>> (0.0, 0.5, 1.0) == color == from_color == from_pixel True ```
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.com/questions/3357581/using-python-class-as-a-data-container/)” where @joe-kington had a good point to use built-in `namedtuple`. **Question** In section 8.3.4 of python 2.7 documentation there is good [example](https://docs.python.org/2.7/library/collections.html#collections.somenamedtuple._fields) on how to combine several named tuples. My question is how to achieve the reverse? **Example** Considering the example from documentation: ``` >>> p._fields # view the field names ('x', 'y') >>> Color = namedtuple('Color', 'red green blue') >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0) ``` How can I deduce a “Color” or a “Point” instance from a “Pixel” instance? Preferably in *pythonic* spirit.
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here it is. By the way, if you need this operation often, you may create a function for `color_ins` creation, based on `pixel_ins`. Or even for any subnamedtuple! ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) pixel_ins = Pixel(x=11, y=22, red=128, green=255, blue=0) color_ins = Color._make(getattr(pixel_ins, field) for field in Color._fields) print color_ins ``` Output: `Color(red=128, green=255, blue=0)` Function for extracting arbitrary subnamedtuple (without error handling): ``` def extract_sub_namedtuple(parent_ins, child_cls): return child_cls._make(getattr(parent_ins, field) for field in child_cls._fields) color_ins = extract_sub_namedtuple(pixel_ins, Color) point_ins = extract_sub_namedtuple(pixel_ins, Point) ```
Here's an alternative implementation of Nikolay Prokopyev's `extract_sub_namedtuple` that uses a dictionary instead of `getattr`. ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) def extract_sub_namedtuple(tup, subtype): d = tup._asdict() return subtype(**{k:d[k] for k in subtype._fields}) pix = Pixel(11, 22, 128, 255, 0) point = extract_sub_namedtuple(pix, Point) color = extract_sub_namedtuple(pix, Color) print(point, color) ``` **output** ``` Point(x=11, y=22) Color(red=128, green=255, blue=0) ``` This *could* be written as a one-liner: ``` def extract_sub_namedtuple(tup, subtype): return subtype(**{k:tup._asdict()[k] for k in subtype._fields}) ``` but it's less efficient because it has to call `tup._asdict()` for each field in `subtype._fields`. Of course, for these specific namedtuples, you can just do ``` point = Point(*pix[:2]) color = Color(*pix[2:]) ``` but that's not very elegant because it hard-codes the parent field positions and lengths. FWIW, there's code to combine multiple namedtuples into one namedtuple, preserving field order and skipping duplicate fields in [this answer](https://stackoverflow.com/a/28942143/4014959).
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.com/questions/3357581/using-python-class-as-a-data-container/)” where @joe-kington had a good point to use built-in `namedtuple`. **Question** In section 8.3.4 of python 2.7 documentation there is good [example](https://docs.python.org/2.7/library/collections.html#collections.somenamedtuple._fields) on how to combine several named tuples. My question is how to achieve the reverse? **Example** Considering the example from documentation: ``` >>> p._fields # view the field names ('x', 'y') >>> Color = namedtuple('Color', 'red green blue') >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0) ``` How can I deduce a “Color” or a “Point” instance from a “Pixel” instance? Preferably in *pythonic* spirit.
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here it is. By the way, if you need this operation often, you may create a function for `color_ins` creation, based on `pixel_ins`. Or even for any subnamedtuple! ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) pixel_ins = Pixel(x=11, y=22, red=128, green=255, blue=0) color_ins = Color._make(getattr(pixel_ins, field) for field in Color._fields) print color_ins ``` Output: `Color(red=128, green=255, blue=0)` Function for extracting arbitrary subnamedtuple (without error handling): ``` def extract_sub_namedtuple(parent_ins, child_cls): return child_cls._make(getattr(parent_ins, field) for field in child_cls._fields) color_ins = extract_sub_namedtuple(pixel_ins, Color) point_ins = extract_sub_namedtuple(pixel_ins, Point) ```
Another way you could do this is to make the arguments for "Pixel" align with what you actually want instead of flattening all of the arguments for its constituent parts. Instead of combining `Point._fields + Color._fields` to get the fields for Pixel, I think you should just have two parameters: `location` and `color`. These two fields could be initialized with your other tuples and you wouldn't have to do any inference. For example: ```py # Instead of Pixel(x=11, y=22, red=128, green=255, blue=0) pixel_ins = Pixel(Point(x=11, y=22), Color(red=128, green=255, blue=0)) # Get the named tuples that the pixel is parameterized by pixel_color = pixel_ins.color pixel_point = pixel_ins.location ``` By mashing all the parameters together (e.g. x, y, red, green, and blue all on the main object) you don't really gain anything, but you lose a lot of legibility. Flattening the parameters also introduces a bug if your namedtuple parameters share fields: ```py from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Hue = namedtuple('Hue', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields + Hue._fields) # Results in: # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # File "C:\Program Files\Python38\lib\collections\__init__.py", line 370, in namedtuple # raise ValueError(f'Encountered duplicate field name: {name!r}') # ValueError: Encountered duplicate field name: 'red' ```
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.com/questions/3357581/using-python-class-as-a-data-container/)” where @joe-kington had a good point to use built-in `namedtuple`. **Question** In section 8.3.4 of python 2.7 documentation there is good [example](https://docs.python.org/2.7/library/collections.html#collections.somenamedtuple._fields) on how to combine several named tuples. My question is how to achieve the reverse? **Example** Considering the example from documentation: ``` >>> p._fields # view the field names ('x', 'y') >>> Color = namedtuple('Color', 'red green blue') >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0) ``` How can I deduce a “Color” or a “Point” instance from a “Pixel” instance? Preferably in *pythonic* spirit.
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here it is. By the way, if you need this operation often, you may create a function for `color_ins` creation, based on `pixel_ins`. Or even for any subnamedtuple! ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) pixel_ins = Pixel(x=11, y=22, red=128, green=255, blue=0) color_ins = Color._make(getattr(pixel_ins, field) for field in Color._fields) print color_ins ``` Output: `Color(red=128, green=255, blue=0)` Function for extracting arbitrary subnamedtuple (without error handling): ``` def extract_sub_namedtuple(parent_ins, child_cls): return child_cls._make(getattr(parent_ins, field) for field in child_cls._fields) color_ins = extract_sub_namedtuple(pixel_ins, Color) point_ins = extract_sub_namedtuple(pixel_ins, Point) ```
**Background** Originally I've asked this question because I had to support some spaghetti codebase that used tuples a lot but not giving any explanation about the values inside them. After some refactoring, I noticed that I need to extract some typed information from other tuples and was looking for some boilerplate free and type-safe way of doing it. **Solution** You can subclass named tuple definition and implement a custom `__new__` method to support that, optionally carrying out some data formatting and validation on the way. See this [reference](https://jfine-python-classes.readthedocs.io/en/latest/subclass-tuple.html#) for more details. **Example** ```py from __future__ import annotations from collections import namedtuple from typing import Union, Tuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) # Redeclare "Color" to provide custom creation method # that can deduce values from various different types class Color(Color): def __new__(cls, *subject: Union[Pixel, Color, Tuple[float, float, float]]) -> Color: # If got only one argument either of type "Pixel" or "Color" if len(subject) == 1 and isinstance((it := subject[0]), (Pixel, Color)): # Create from invalidated color properties return super().__new__(cls, *cls.invalidate(it.red, it.green, it.blue)) else: # Else treat it as raw values and by-pass them after invalidation return super().__new__(cls, *cls.invalidate(*subject)) @classmethod def invalidate(cls, r, g, b) -> Tuple[float, float, float]: # Convert values to float r, g, b = (float(it) for it in (r, g, b)) # Ensure that all values are in valid range assert all(0 <= it <= 1.0 for it in (r, g, b)), 'Some RGB values are invalid' return r, g, b ``` Now you can instantiate `Color` from any of the supported value types (`Color`, `Pixel`, a triplet of numbers) without boilerplate. ```py color = Color(0, 0.5, 1) from_color = Color(color) from_pixel = Color(Pixel(3.4, 5.6, 0, 0.5, 1)) ``` And you can verify all are equal values: ```py >>> (0.0, 0.5, 1.0) == color == from_color == from_pixel True ```
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.com/questions/3357581/using-python-class-as-a-data-container/)” where @joe-kington had a good point to use built-in `namedtuple`. **Question** In section 8.3.4 of python 2.7 documentation there is good [example](https://docs.python.org/2.7/library/collections.html#collections.somenamedtuple._fields) on how to combine several named tuples. My question is how to achieve the reverse? **Example** Considering the example from documentation: ``` >>> p._fields # view the field names ('x', 'y') >>> Color = namedtuple('Color', 'red green blue') >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0) ``` How can I deduce a “Color” or a “Point” instance from a “Pixel” instance? Preferably in *pythonic* spirit.
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here's an alternative implementation of Nikolay Prokopyev's `extract_sub_namedtuple` that uses a dictionary instead of `getattr`. ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) def extract_sub_namedtuple(tup, subtype): d = tup._asdict() return subtype(**{k:d[k] for k in subtype._fields}) pix = Pixel(11, 22, 128, 255, 0) point = extract_sub_namedtuple(pix, Point) color = extract_sub_namedtuple(pix, Color) print(point, color) ``` **output** ``` Point(x=11, y=22) Color(red=128, green=255, blue=0) ``` This *could* be written as a one-liner: ``` def extract_sub_namedtuple(tup, subtype): return subtype(**{k:tup._asdict()[k] for k in subtype._fields}) ``` but it's less efficient because it has to call `tup._asdict()` for each field in `subtype._fields`. Of course, for these specific namedtuples, you can just do ``` point = Point(*pix[:2]) color = Color(*pix[2:]) ``` but that's not very elegant because it hard-codes the parent field positions and lengths. FWIW, there's code to combine multiple namedtuples into one namedtuple, preserving field order and skipping duplicate fields in [this answer](https://stackoverflow.com/a/28942143/4014959).
Another way you could do this is to make the arguments for "Pixel" align with what you actually want instead of flattening all of the arguments for its constituent parts. Instead of combining `Point._fields + Color._fields` to get the fields for Pixel, I think you should just have two parameters: `location` and `color`. These two fields could be initialized with your other tuples and you wouldn't have to do any inference. For example: ```py # Instead of Pixel(x=11, y=22, red=128, green=255, blue=0) pixel_ins = Pixel(Point(x=11, y=22), Color(red=128, green=255, blue=0)) # Get the named tuples that the pixel is parameterized by pixel_color = pixel_ins.color pixel_point = pixel_ins.location ``` By mashing all the parameters together (e.g. x, y, red, green, and blue all on the main object) you don't really gain anything, but you lose a lot of legibility. Flattening the parameters also introduces a bug if your namedtuple parameters share fields: ```py from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Hue = namedtuple('Hue', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields + Hue._fields) # Results in: # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # File "C:\Program Files\Python38\lib\collections\__init__.py", line 370, in namedtuple # raise ValueError(f'Encountered duplicate field name: {name!r}') # ValueError: Encountered duplicate field name: 'red' ```
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.com/questions/3357581/using-python-class-as-a-data-container/)” where @joe-kington had a good point to use built-in `namedtuple`. **Question** In section 8.3.4 of python 2.7 documentation there is good [example](https://docs.python.org/2.7/library/collections.html#collections.somenamedtuple._fields) on how to combine several named tuples. My question is how to achieve the reverse? **Example** Considering the example from documentation: ``` >>> p._fields # view the field names ('x', 'y') >>> Color = namedtuple('Color', 'red green blue') >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields) >>> Pixel(11, 22, 128, 255, 0) Pixel(x=11, y=22, red=128, green=255, blue=0) ``` How can I deduce a “Color” or a “Point” instance from a “Pixel” instance? Preferably in *pythonic* spirit.
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here's an alternative implementation of Nikolay Prokopyev's `extract_sub_namedtuple` that uses a dictionary instead of `getattr`. ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) def extract_sub_namedtuple(tup, subtype): d = tup._asdict() return subtype(**{k:d[k] for k in subtype._fields}) pix = Pixel(11, 22, 128, 255, 0) point = extract_sub_namedtuple(pix, Point) color = extract_sub_namedtuple(pix, Color) print(point, color) ``` **output** ``` Point(x=11, y=22) Color(red=128, green=255, blue=0) ``` This *could* be written as a one-liner: ``` def extract_sub_namedtuple(tup, subtype): return subtype(**{k:tup._asdict()[k] for k in subtype._fields}) ``` but it's less efficient because it has to call `tup._asdict()` for each field in `subtype._fields`. Of course, for these specific namedtuples, you can just do ``` point = Point(*pix[:2]) color = Color(*pix[2:]) ``` but that's not very elegant because it hard-codes the parent field positions and lengths. FWIW, there's code to combine multiple namedtuples into one namedtuple, preserving field order and skipping duplicate fields in [this answer](https://stackoverflow.com/a/28942143/4014959).
**Background** Originally I've asked this question because I had to support some spaghetti codebase that used tuples a lot but not giving any explanation about the values inside them. After some refactoring, I noticed that I need to extract some typed information from other tuples and was looking for some boilerplate free and type-safe way of doing it. **Solution** You can subclass named tuple definition and implement a custom `__new__` method to support that, optionally carrying out some data formatting and validation on the way. See this [reference](https://jfine-python-classes.readthedocs.io/en/latest/subclass-tuple.html#) for more details. **Example** ```py from __future__ import annotations from collections import namedtuple from typing import Union, Tuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) # Redeclare "Color" to provide custom creation method # that can deduce values from various different types class Color(Color): def __new__(cls, *subject: Union[Pixel, Color, Tuple[float, float, float]]) -> Color: # If got only one argument either of type "Pixel" or "Color" if len(subject) == 1 and isinstance((it := subject[0]), (Pixel, Color)): # Create from invalidated color properties return super().__new__(cls, *cls.invalidate(it.red, it.green, it.blue)) else: # Else treat it as raw values and by-pass them after invalidation return super().__new__(cls, *cls.invalidate(*subject)) @classmethod def invalidate(cls, r, g, b) -> Tuple[float, float, float]: # Convert values to float r, g, b = (float(it) for it in (r, g, b)) # Ensure that all values are in valid range assert all(0 <= it <= 1.0 for it in (r, g, b)), 'Some RGB values are invalid' return r, g, b ``` Now you can instantiate `Color` from any of the supported value types (`Color`, `Pixel`, a triplet of numbers) without boilerplate. ```py color = Color(0, 0.5, 1) from_color = Color(color) from_pixel = Color(Pixel(3.4, 5.6, 0, 0.5, 1)) ``` And you can verify all are equal values: ```py >>> (0.0, 0.5, 1.0) == color == from_color == from_pixel True ```
44,535,068
I want to cover a image with a transparent solid color overlay in the shape of a black-white mask Currently I'm using the following java code to implement this. ``` redImg = new Mat(image.size(), image.type(), new Scalar(255, 0, 0)); redImg.copyTo(image, mask); ``` I'm not familiar with the python api. So I want to know if there any alternative api in python. Is there any better implementation? image: [![src img](https://i.stack.imgur.com/72iEF.jpg)](https://i.stack.imgur.com/72iEF.jpg) mask: [![mask](https://i.stack.imgur.com/dd1l4.jpg)](https://i.stack.imgur.com/dd1l4.jpg) what i want: [![what i want](https://i.stack.imgur.com/YP2d1.jpg)](https://i.stack.imgur.com/YP2d1.jpg)
2017/06/14
[ "https://Stackoverflow.com/questions/44535068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640554/" ]
Now after I deal with all this Python, OpenCV, Numpy thing for a while, I find out it's quite simple to implement this with code: ``` image[mask] = (0, 0, 255) ``` -------------- the original answer -------------- I solved this by the following code: ``` redImg = np.zeros(image.shape, image.dtype) redImg[:,:] = (0, 0, 255) redMask = cv2.bitwise_and(redImg, redImg, mask=mask) cv2.addWeighted(redMask, 1, image, 1, 0, image) ```
The idea is to convert the mask to a binary format where pixels are either `0` (black) or `255` (white). White pixels represent sections that are kept while black sections are thrown away. Then set all white pixels on the mask to your desired `BGR` color. **Input image and mask** ![](https://i.stack.imgur.com/OfGZF.png) ![](https://i.stack.imgur.com/o9v6s.png) **Result** ![](https://i.stack.imgur.com/qCTun.png) Code ``` import cv2 image = cv2.imread('1.jpg') mask = cv2.imread('mask.jpg', 0) mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] image[mask==255] = (36,255,12) cv2.imshow('image', image) cv2.imshow('mask', mask) cv2.waitKey() ```
44,535,068
I want to cover a image with a transparent solid color overlay in the shape of a black-white mask Currently I'm using the following java code to implement this. ``` redImg = new Mat(image.size(), image.type(), new Scalar(255, 0, 0)); redImg.copyTo(image, mask); ``` I'm not familiar with the python api. So I want to know if there any alternative api in python. Is there any better implementation? image: [![src img](https://i.stack.imgur.com/72iEF.jpg)](https://i.stack.imgur.com/72iEF.jpg) mask: [![mask](https://i.stack.imgur.com/dd1l4.jpg)](https://i.stack.imgur.com/dd1l4.jpg) what i want: [![what i want](https://i.stack.imgur.com/YP2d1.jpg)](https://i.stack.imgur.com/YP2d1.jpg)
2017/06/14
[ "https://Stackoverflow.com/questions/44535068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640554/" ]
Now after I deal with all this Python, OpenCV, Numpy thing for a while, I find out it's quite simple to implement this with code: ``` image[mask] = (0, 0, 255) ``` -------------- the original answer -------------- I solved this by the following code: ``` redImg = np.zeros(image.shape, image.dtype) redImg[:,:] = (0, 0, 255) redMask = cv2.bitwise_and(redImg, redImg, mask=mask) cv2.addWeighted(redMask, 1, image, 1, 0, image) ```
this is what worked for me: ``` red = np.ones(mask.shape) red = red*255 img[:,:,0][mask>0] = red[mask>0] ``` so I made a 2d array with solid 255 values and replaced it with my image's red band in pixels where the mask is not zero. [redmask](https://i.stack.imgur.com/kYbMV.png)
44,535,068
I want to cover a image with a transparent solid color overlay in the shape of a black-white mask Currently I'm using the following java code to implement this. ``` redImg = new Mat(image.size(), image.type(), new Scalar(255, 0, 0)); redImg.copyTo(image, mask); ``` I'm not familiar with the python api. So I want to know if there any alternative api in python. Is there any better implementation? image: [![src img](https://i.stack.imgur.com/72iEF.jpg)](https://i.stack.imgur.com/72iEF.jpg) mask: [![mask](https://i.stack.imgur.com/dd1l4.jpg)](https://i.stack.imgur.com/dd1l4.jpg) what i want: [![what i want](https://i.stack.imgur.com/YP2d1.jpg)](https://i.stack.imgur.com/YP2d1.jpg)
2017/06/14
[ "https://Stackoverflow.com/questions/44535068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640554/" ]
The idea is to convert the mask to a binary format where pixels are either `0` (black) or `255` (white). White pixels represent sections that are kept while black sections are thrown away. Then set all white pixels on the mask to your desired `BGR` color. **Input image and mask** ![](https://i.stack.imgur.com/OfGZF.png) ![](https://i.stack.imgur.com/o9v6s.png) **Result** ![](https://i.stack.imgur.com/qCTun.png) Code ``` import cv2 image = cv2.imread('1.jpg') mask = cv2.imread('mask.jpg', 0) mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] image[mask==255] = (36,255,12) cv2.imshow('image', image) cv2.imshow('mask', mask) cv2.waitKey() ```
this is what worked for me: ``` red = np.ones(mask.shape) red = red*255 img[:,:,0][mask>0] = red[mask>0] ``` so I made a 2d array with solid 255 values and replaced it with my image's red band in pixels where the mask is not zero. [redmask](https://i.stack.imgur.com/kYbMV.png)
57,251,368
Kindly need some help please :) I have two date-time's i am using the date-time.combine to concatenate one is datetime.date (pretty much todays date) - the other is datetime.time (which is a manually defined time) keep getting stuck with the below error; ``` Traceback (most recent call last): File "sunsetTimer.py", line 167, in <module> if currentTime >= lightOffDT: TypeError: can't compare datetime.datetime to tuple ``` Rather new at Python, so probably a really stupid question. have tried pulling from the tuple with lightOffDT[0] - but get an error that an integer is required. when I print, it prints as a normal date-time e.g 2019-07-29 23:30:00 ``` todayDate = datetime.date.today() off1 = datetime.time(23,30,0) lightOffDT = datetime.datetime.combine(todayDate,off1) currentTime >= lightOffDT: #currentTime is today (datetime) ``` I would like to compare the combined date-time so I can compare to the current date and time. currentTime is calculated as: ``` import tzlocal local_timezone = tzlocal.get_localzone() currentTime = datetime.datetime.now(local_timezone) ``` TOTAL CODE; - This is on a Raspberry pi. ``` from datetime import datetime, timedelta from time import localtime, strftime import RPi.GPIO as GPIO import datetime import ephem import pytz import sys import tzlocal Mon = 0 Tue = 1 Wed = 2 Thu = 3 Fri = 4 Sat = 5 Sun = 6 Pin11 = 11 # pin11 Pin12 = 12 # pin12 GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(Pin11, GPIO.OUT) # Set LedPin 11 mode is output / deck lights GPIO.setup(Pin12, GPIO.OUT) # Set LedPin 11 mode is output / path lights SEC30 = timedelta(seconds=30) home = ephem.Observer() # replace lat, long, and elevation to yours home.lat = '-37.076732' home.long = '174.939366' home.elevation = 5 local_timezone = tzlocal.get_localzone() # Gets time zone Pacific/Auckland sun = ephem.Sun() sun.compute(home) fmt = "%d-%b-%Y %H%MUTC" #Weekend timers #def lightonTimes_weekend(): #on1 = set via sunsettime #on2 = datetime.time(04,30,00) def lightoffTimes_Deviate(): off1 = datetime.time(23,30,0) return off1 # Weekday timers def lightonTimes_Normal(): #on1 = set via sunsettime on2 = datetime.time(4,30,0) return on2 def lightoffTimes_Normal(): off1 = datetime.time(22,30,0) off2 = datetime.time(5,30,0) return off1, off2 def dateTimeTomorrow(): tomorrowDate = datetime.date.today() + datetime.timedelta(days=1) return tomorrowDate def localtimesTZ(): currentTime = datetime.datetime.now(local_timezone) # Current New Zealand TimeZones. todayDate = datetime.date.today() tday = todayDate.weekday() return currentTime, tday, todayDate #def ephemtimes_Tomorrow(): def ephemtimes(): #sun.compute(home) nextrise = home.next_rising(sun) nextset = home.previous_setting(sun) nextriseutc= nextrise.datetime() + SEC30 nextsetutc= nextset.datetime() + SEC30 sunrise = nextriseutc.replace(tzinfo=pytz.utc).astimezone(local_timezone) sunset = nextsetutc.replace(tzinfo=pytz.utc).astimezone(local_timezone) sunriseTime = sunrise.time() sunsetTime = sunset.time() #print "Sunrise local ", sunrise #print "Sunset local ", sunset #print "Current time ", currentTime #print "Local Time: ", local_timezone #print "next sunrise: ", nextriseutc.strftime(fmt) #print "next sunset: ", nextsetutc.strftime(fmt) return sunrise, sunriseTime, sunset, sunsetTime if __name__ == '__main__': sunrise, sunriseTime, sunset, sunsetTime = ephemtimes() # calls times function to pull sunrise, sunset times. currentTime, tday, todayDate = localtimesTZ() #print "Current Time " + str(currentTime) #print todayDate #print sunrise #print "Sunset time " + str(sunset) #print sunriseTime #print sunsetTime #print tday tomorrowDate = dateTimeTomorrow() #print tomorrowDate # start loop here #off1 >= lightoffTimes_Deviate() if (tday == Sun) or (tday == Mon): # timer for weekend (Sunday or Monday) #CurrentTime & SunSet time are in full datetime - converted to Local Time if currentTime > sunset: GPIO.output(Pin11, GPIO.LOW) # Turn GPIO pins on GPIO.output(Pin12, GPIO.LOW) # *********************************** off1 = lightoffTimes_Deviate() #get off time print 'error below' print todayDate print off1 #### this is where the problems start!!! lightOffDT = datetime.datetime.combine(todayDate,off1) print lightOffDT #print "light off time " + str(lightoffdatetime) while True: currentTime = localtimesTZ() if currentTime >= lightOffDT: GPIO.output(Pin11, GPIO.HIGH) # Turn GPIO pins on GPIO.output(Pin12, GPIO.HIGH) break else: os.system('cls' if os.name == 'nt' else 'clear') print "Current Time " + str(lightoffdatetimepython) time.sleep(5) ```
2019/07/29
[ "https://Stackoverflow.com/questions/57251368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11847814/" ]
Look at how you have defined `currentTime`: ``` currentTime = localtimesTZ() ``` Your `localtimesTZ()` actually returns a tuple `currentTime, tday, todayDate`, which is what is assigned to `currentTime`. Not sure why you are doing that; returning just the `currentTime` should be sufficient, since it is a `datetime.datetime` object. Then you try and compare that tuple to `lightOffDT`, which is a `datetime.datetime` object. Hence the error. You could try: ``` if currentTime[0] >= lightOffDT: ``` That would actually compare two `datetime.datetime` objects.
It sounds like you are just trying to do a simple comparison of a manually set date and check if that day is today. If that is the case it would be simpler to use the same class datetime. Below is a simple example checking if today (manually defined) is today (defined by python) from datetime import datetime ``` todayDate = datetime.today() someOtherDate = datetime(year=2019,month=7,day=29) if todayDate.date() == someOtherTime.date(): print(True) ``` outputs ``` True ```
57,251,368
Kindly need some help please :) I have two date-time's i am using the date-time.combine to concatenate one is datetime.date (pretty much todays date) - the other is datetime.time (which is a manually defined time) keep getting stuck with the below error; ``` Traceback (most recent call last): File "sunsetTimer.py", line 167, in <module> if currentTime >= lightOffDT: TypeError: can't compare datetime.datetime to tuple ``` Rather new at Python, so probably a really stupid question. have tried pulling from the tuple with lightOffDT[0] - but get an error that an integer is required. when I print, it prints as a normal date-time e.g 2019-07-29 23:30:00 ``` todayDate = datetime.date.today() off1 = datetime.time(23,30,0) lightOffDT = datetime.datetime.combine(todayDate,off1) currentTime >= lightOffDT: #currentTime is today (datetime) ``` I would like to compare the combined date-time so I can compare to the current date and time. currentTime is calculated as: ``` import tzlocal local_timezone = tzlocal.get_localzone() currentTime = datetime.datetime.now(local_timezone) ``` TOTAL CODE; - This is on a Raspberry pi. ``` from datetime import datetime, timedelta from time import localtime, strftime import RPi.GPIO as GPIO import datetime import ephem import pytz import sys import tzlocal Mon = 0 Tue = 1 Wed = 2 Thu = 3 Fri = 4 Sat = 5 Sun = 6 Pin11 = 11 # pin11 Pin12 = 12 # pin12 GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(Pin11, GPIO.OUT) # Set LedPin 11 mode is output / deck lights GPIO.setup(Pin12, GPIO.OUT) # Set LedPin 11 mode is output / path lights SEC30 = timedelta(seconds=30) home = ephem.Observer() # replace lat, long, and elevation to yours home.lat = '-37.076732' home.long = '174.939366' home.elevation = 5 local_timezone = tzlocal.get_localzone() # Gets time zone Pacific/Auckland sun = ephem.Sun() sun.compute(home) fmt = "%d-%b-%Y %H%MUTC" #Weekend timers #def lightonTimes_weekend(): #on1 = set via sunsettime #on2 = datetime.time(04,30,00) def lightoffTimes_Deviate(): off1 = datetime.time(23,30,0) return off1 # Weekday timers def lightonTimes_Normal(): #on1 = set via sunsettime on2 = datetime.time(4,30,0) return on2 def lightoffTimes_Normal(): off1 = datetime.time(22,30,0) off2 = datetime.time(5,30,0) return off1, off2 def dateTimeTomorrow(): tomorrowDate = datetime.date.today() + datetime.timedelta(days=1) return tomorrowDate def localtimesTZ(): currentTime = datetime.datetime.now(local_timezone) # Current New Zealand TimeZones. todayDate = datetime.date.today() tday = todayDate.weekday() return currentTime, tday, todayDate #def ephemtimes_Tomorrow(): def ephemtimes(): #sun.compute(home) nextrise = home.next_rising(sun) nextset = home.previous_setting(sun) nextriseutc= nextrise.datetime() + SEC30 nextsetutc= nextset.datetime() + SEC30 sunrise = nextriseutc.replace(tzinfo=pytz.utc).astimezone(local_timezone) sunset = nextsetutc.replace(tzinfo=pytz.utc).astimezone(local_timezone) sunriseTime = sunrise.time() sunsetTime = sunset.time() #print "Sunrise local ", sunrise #print "Sunset local ", sunset #print "Current time ", currentTime #print "Local Time: ", local_timezone #print "next sunrise: ", nextriseutc.strftime(fmt) #print "next sunset: ", nextsetutc.strftime(fmt) return sunrise, sunriseTime, sunset, sunsetTime if __name__ == '__main__': sunrise, sunriseTime, sunset, sunsetTime = ephemtimes() # calls times function to pull sunrise, sunset times. currentTime, tday, todayDate = localtimesTZ() #print "Current Time " + str(currentTime) #print todayDate #print sunrise #print "Sunset time " + str(sunset) #print sunriseTime #print sunsetTime #print tday tomorrowDate = dateTimeTomorrow() #print tomorrowDate # start loop here #off1 >= lightoffTimes_Deviate() if (tday == Sun) or (tday == Mon): # timer for weekend (Sunday or Monday) #CurrentTime & SunSet time are in full datetime - converted to Local Time if currentTime > sunset: GPIO.output(Pin11, GPIO.LOW) # Turn GPIO pins on GPIO.output(Pin12, GPIO.LOW) # *********************************** off1 = lightoffTimes_Deviate() #get off time print 'error below' print todayDate print off1 #### this is where the problems start!!! lightOffDT = datetime.datetime.combine(todayDate,off1) print lightOffDT #print "light off time " + str(lightoffdatetime) while True: currentTime = localtimesTZ() if currentTime >= lightOffDT: GPIO.output(Pin11, GPIO.HIGH) # Turn GPIO pins on GPIO.output(Pin12, GPIO.HIGH) break else: os.system('cls' if os.name == 'nt' else 'clear') print "Current Time " + str(lightoffdatetimepython) time.sleep(5) ```
2019/07/29
[ "https://Stackoverflow.com/questions/57251368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11847814/" ]
Look at how you have defined `currentTime`: ``` currentTime = localtimesTZ() ``` Your `localtimesTZ()` actually returns a tuple `currentTime, tday, todayDate`, which is what is assigned to `currentTime`. Not sure why you are doing that; returning just the `currentTime` should be sufficient, since it is a `datetime.datetime` object. Then you try and compare that tuple to `lightOffDT`, which is a `datetime.datetime` object. Hence the error. You could try: ``` if currentTime[0] >= lightOffDT: ``` That would actually compare two `datetime.datetime` objects.
i think you are trying to compare a datetime with a tuple. This is the line that adds `currentTime` to a tuple: ``` currentTime, tday, todayDate = localtimesTZ() ``` You therefore need the index of `currentTime` from the tuple for comparison i.e ``` if currentTime[0] >= lightOffDT ``` Index is 0 because currentTime is the first item in the tuple.
6,265,517
Can anyone name a language with all the following properties: 1. Has algebraic data types 2. Has good support for linear algebra 3. Is fast(-er than python, at least) 4. Has at least some functional programming ability (I don't need monads) 5. Has been heard of, is not dead, and can interface on a C calling level
2011/06/07
[ "https://Stackoverflow.com/questions/6265517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787480/" ]
Scala ===== According to [Wikipedia](http://en.wikipedia.org/wiki/Algebraic_data_type) it has algebraic datatypes. And it is [fast](http://www.scribd.com/doc/57021877/Loop-Recognition-in-C-Java-Go-Scala). Scala is both functional and object oriented. And it's a young language with a growing userbase but still to some extent compatible with Java. There is a Scala library [Scalala](http://code.google.com/p/scalala/) for linear algebra: > > A high performance numeric linear algebra library for Scala, with rich Matlab-like operators on vectors and matrices; a library of numerical routines > > >
I'd say C and C++. And they work well with: * [Matlab](http://www.mathworks.com/products/matlab/) * [Maple](http://www.maplesoft.com/products/Maple/)
6,265,517
Can anyone name a language with all the following properties: 1. Has algebraic data types 2. Has good support for linear algebra 3. Is fast(-er than python, at least) 4. Has at least some functional programming ability (I don't need monads) 5. Has been heard of, is not dead, and can interface on a C calling level
2011/06/07
[ "https://Stackoverflow.com/questions/6265517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787480/" ]
I have my own favorite pet languages, and this isn't one of them, but it sounds to me like [R](http://www.r-project.org/) is probably what you are looking for. It seems to be *the* hot new language these days for people doing heavy math. As for the "faster than Python" part, that's tough to say. In general, languages don't really have a speed; language *implementations* do. So the only way to tell really is to compare your time-constraining algorithm on each implementation you can get.
I'd say C and C++. And they work well with: * [Matlab](http://www.mathworks.com/products/matlab/) * [Maple](http://www.maplesoft.com/products/Maple/)
6,265,517
Can anyone name a language with all the following properties: 1. Has algebraic data types 2. Has good support for linear algebra 3. Is fast(-er than python, at least) 4. Has at least some functional programming ability (I don't need monads) 5. Has been heard of, is not dead, and can interface on a C calling level
2011/06/07
[ "https://Stackoverflow.com/questions/6265517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787480/" ]
Scala ===== According to [Wikipedia](http://en.wikipedia.org/wiki/Algebraic_data_type) it has algebraic datatypes. And it is [fast](http://www.scribd.com/doc/57021877/Loop-Recognition-in-C-Java-Go-Scala). Scala is both functional and object oriented. And it's a young language with a growing userbase but still to some extent compatible with Java. There is a Scala library [Scalala](http://code.google.com/p/scalala/) for linear algebra: > > A high performance numeric linear algebra library for Scala, with rich Matlab-like operators on vectors and matrices; a library of numerical routines > > >
I have my own favorite pet languages, and this isn't one of them, but it sounds to me like [R](http://www.r-project.org/) is probably what you are looking for. It seems to be *the* hot new language these days for people doing heavy math. As for the "faster than Python" part, that's tough to say. In general, languages don't really have a speed; language *implementations* do. So the only way to tell really is to compare your time-constraining algorithm on each implementation you can get.
54,722,389
First off, let me say that yes I have researched this extensively for a few days now with no luck. I have looked at numerous examples and similar situations such as [this one](https://stackoverflow.com/questions/35149265/python-super-method-class-name-not-defined), but so far nothing has been able to resolve me issue. My problem is I have a Python project that has a primary class, with two nested classes (yea yea I know), one of those classes is a subclass of the first. I can not figure out why I keep getting `NameError: global name 'InnerSubClass' is not defined`. I understand scoping (both classes in question are in the same scope) but nothing I try seems to resolve the issue (I want to keep the two classes nested at a minimum) despite this problem working for other people. Here is a simple example of what I am trying to do: ``` class SomeClass(object): def __init__(self): """lots of other working stuff""" class MainClass(object): def __init__(self): self.stuff = [] self.moreStuffs = [] class InnerClass(object): def __init__(self, thing, otherThing): self.thing = thing self.otherThing = otherThing self.otherStuff = [] class InnerSubClass(InnerClass): def __init__(self, thing, otherThing, newThing): super(InnerSubClass).__init__(thing, otherThing) self.newThing = newThing """other code that worked before the addition of 'InnerSubClass'""" def doSomething(self): innerclass = self.InnerSubClass('thisthing', 'thatthing', 'thingthing') print("just more thing words %s" % innerclass.newThing) myThing = MainClass() myThing.doSomething() ``` I have tried changing `super(InnerSubClass).__init__(thing, otherThing)` to `super(InnerClass.InnerSubClass).__init__(thing, otherThing)` and even `super(MainClass.InnerClass.InnerSubClass).__init__(thing, otherThing)` with no success. I made "InnerSubClass" inherit straight from object `InnerSubClass(object):` etc, and it still doesn't work. Granted I am far from a seasoned python developer and come from mostly other compiled OO languages, and can't seem to wrap my head around why this isn't working. If I get rid of the "InnerSubClass", everything works just fine. It doesn't seem like python offers "private" classes and functions like other languages, which is fine but I would like to utilize the nesting to at least keep objects "lumped" together. In this case, nothing should be instantiating "InnerClass" or "InnerSubClass" except functions in "MainClass". Please provide helpful advice and explain why it doesn't work as expected with background information on how this should be done properly. If this was as simple as it seems, it would have been figured out by now. **edit:** for clarification, this is only for v2
2019/02/16
[ "https://Stackoverflow.com/questions/54722389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348576/" ]
[Here](https://stackoverflow.com/questions/38778158/how-to-do-nested-class-and-inherit-inside-the-class?rq=1) they do it like this ``` super(MainClass.InnerSubClass, self).__init__(thing, otherThing) ``` So that you can test it here is the full working example ``` class SomeClass(object): def __init__(self): """lots of other working stuff""" class MainClass(object): def __init__(self): self.stuff = [] self.moreStuffs = [] class InnerClass(object): def __init__(self, thing, otherThing): self.thing = thing self.otherThing = otherThing self.otherStuff = [] class InnerSubClass(InnerClass): def __init__(self, thing, otherThing, newThing): super(MainClass.InnerSubClass, self).__init__(thing, otherThing) self.newThing = newThing """other code that worked before the addition of 'InnerSubClass'""" def doSomething(self): innerclass = self.InnerSubClass('thisthing', 'thatthing', 'thingthing') print("just more thing words %s" % innerclass.newThing) print("and I also inherit from InnerClass %s" % innerclass.otherThing) myThing = MainClass() myThing.doSomething() ``` The output is ``` just more thing words thingthing and I also inherit from InnerClass thatthing ```
If you have reasons for not using `MainClass.InnerSubClass`, you can also use `type(self)` or `self.__class__` ([OK, but which one](https://stackoverflow.com/questions/1060499/difference-between-typeobj-and-obj-class)) inside `__init__` to get the containing class. This works well lots of layers deep (which shouldn't happen anyway), and requires the argument passed to `super` to be the type of the instance (which it should be anyway) **but breaks if you subclass**, as seen [here](https://ideone.com/Ld8PAX). The concept might be clearer to you than scoping rules: ``` class MainClass: class Inner: pass class InnerSub(Inner): def __init__(self): print(super(self.__class__)) print(super(type(self))) MainClass().InnerSub() ```
54,722,389
First off, let me say that yes I have researched this extensively for a few days now with no luck. I have looked at numerous examples and similar situations such as [this one](https://stackoverflow.com/questions/35149265/python-super-method-class-name-not-defined), but so far nothing has been able to resolve me issue. My problem is I have a Python project that has a primary class, with two nested classes (yea yea I know), one of those classes is a subclass of the first. I can not figure out why I keep getting `NameError: global name 'InnerSubClass' is not defined`. I understand scoping (both classes in question are in the same scope) but nothing I try seems to resolve the issue (I want to keep the two classes nested at a minimum) despite this problem working for other people. Here is a simple example of what I am trying to do: ``` class SomeClass(object): def __init__(self): """lots of other working stuff""" class MainClass(object): def __init__(self): self.stuff = [] self.moreStuffs = [] class InnerClass(object): def __init__(self, thing, otherThing): self.thing = thing self.otherThing = otherThing self.otherStuff = [] class InnerSubClass(InnerClass): def __init__(self, thing, otherThing, newThing): super(InnerSubClass).__init__(thing, otherThing) self.newThing = newThing """other code that worked before the addition of 'InnerSubClass'""" def doSomething(self): innerclass = self.InnerSubClass('thisthing', 'thatthing', 'thingthing') print("just more thing words %s" % innerclass.newThing) myThing = MainClass() myThing.doSomething() ``` I have tried changing `super(InnerSubClass).__init__(thing, otherThing)` to `super(InnerClass.InnerSubClass).__init__(thing, otherThing)` and even `super(MainClass.InnerClass.InnerSubClass).__init__(thing, otherThing)` with no success. I made "InnerSubClass" inherit straight from object `InnerSubClass(object):` etc, and it still doesn't work. Granted I am far from a seasoned python developer and come from mostly other compiled OO languages, and can't seem to wrap my head around why this isn't working. If I get rid of the "InnerSubClass", everything works just fine. It doesn't seem like python offers "private" classes and functions like other languages, which is fine but I would like to utilize the nesting to at least keep objects "lumped" together. In this case, nothing should be instantiating "InnerClass" or "InnerSubClass" except functions in "MainClass". Please provide helpful advice and explain why it doesn't work as expected with background information on how this should be done properly. If this was as simple as it seems, it would have been figured out by now. **edit:** for clarification, this is only for v2
2019/02/16
[ "https://Stackoverflow.com/questions/54722389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348576/" ]
### There is no "class scope" in lookup order When creating a new class, the code in the body is executed and the resulting names are passed to `type` for creation. Python lookups go from inner to outer, but you don't have a "class level", only the names you define to become attributes/methods of your new class. In fact, if you want to access class variables inside a method, you use `MyClass.attr` instead of simple `attr`. The inheritance works because `InnerSubClass(InnerClass)` occurs inside the class creation. To access `InnerClass` after `MainClass` has been created, do the same as you would for class attributes: `MainClass.InnerClass` Just to include an example: ``` class Outer: out = 1 class Inner: inside = 2 try: print(out) # this is confusing except NameError: print("can't find out") def f(self): try: print(inside) # this is clear except NameError: print("can't find inside") try: print(Inner.inside) # this is less clear except NameError: print("can't find Inner.inside") Outer.Inner().f() # can't find anything ``` Edit: The above is a general view, to apply it directly to your situation, look at your inner classes the way you look at regular class attributes. You'd access these as `MyClass.attr`, where `MyClass` is defined globally. If you replace `attr` with `InnerSubClass`, you get the class (attribute lookup doesn't care about inheritance, but about where the attributes are). A stripped-down example with nested inheriting classes: ``` class MainClass(object): class Inner(object): pass class InnerSub(Inner): def __init__(self): print(super(MainClass.InnerSub)) # note you use MainClass, known globally def f(self): return self.InnerSub() MainClass().f() # prints "<super ...>" and returns a MainCLass.InnerSub object ```
If you have reasons for not using `MainClass.InnerSubClass`, you can also use `type(self)` or `self.__class__` ([OK, but which one](https://stackoverflow.com/questions/1060499/difference-between-typeobj-and-obj-class)) inside `__init__` to get the containing class. This works well lots of layers deep (which shouldn't happen anyway), and requires the argument passed to `super` to be the type of the instance (which it should be anyway) **but breaks if you subclass**, as seen [here](https://ideone.com/Ld8PAX). The concept might be clearer to you than scoping rules: ``` class MainClass: class Inner: pass class InnerSub(Inner): def __init__(self): print(super(self.__class__)) print(super(type(self))) MainClass().InnerSub() ```
17,903,820
code below creates a layout and displays some text in the layout. Next the layout is displayed on the console screen using raw display module from urwid library. (More info on my complete project can be gleaned from questions at [widget advice for a console project](https://stackoverflow.com/questions/17846930/required-widgets-for-displaying-a-1d-console-application) and [urwid for a console project](https://stackoverflow.com/questions/17381319/using-urwid-to-create-a-2d-console-application). My skype help request being [here](https://stackoverflow.com/questions/17846113/widget-to-choose-for-1d-urwid-application).) However running the code fails as an Assertion Error is raised as described below : Error on running code is : `Traceback (most recent call last): File "./yamlUrwidUIPhase6.py", line 98, in <module> main() File "./yamlUrwidUIPhase6.py", line 92, in main form.main() File "./yamlUrwidUIPhase6.py", line 48, in main self.view = formLayout() File "./yamlUrwidUIPhase6.py", line 77, in formLayout ui.draw_screen(dim, frame.render(dim, True)) File "/usr/lib64/python2.7/site-packages/urwid/raw_display.py", line 535, in draw_screen assert self._started AssertionError` The code : ``` import sys sys.path.append('./lib') import os from pprint import pprint import random import urwid ui=urwid.raw_display.Screen() class FormDisplay(object): def __init__(self): global ui self.ui = ui palette = ui.register_palette([ ('Field', 'dark green, bold', 'black'), # information fields, Search: etc. ('Info', 'dark green', 'black'), # information in fields ('Bg', 'black', 'black'), # screen background ('InfoFooterText', 'white', 'dark blue'), # footer text ('InfoFooterHotkey', 'dark cyan, bold', 'dark blue'), # hotkeys in footer text ('InfoFooter', 'black', 'dark blue'), # footer background ('InfoHeaderText', 'white, bold', 'dark blue'), # header text ('InfoHeader', 'black', 'dark blue'), # header background ('BigText', RandomColor(), 'black'), # main menu banner text ('GeneralInfo', 'brown', 'black'), # main menu text ('LastModifiedField', 'dark cyan, bold', 'black'), # Last modified: ('LastModifiedDate', 'dark cyan', 'black'), # info in Last modified: ('PopupMessageText', 'black', 'dark cyan'), # popup message text ('PopupMessageBg', 'black', 'dark cyan'), # popup message background ('SearchBoxHeaderText', 'light gray, bold', 'dark cyan'), # field names in the search box ('SearchBoxHeaderBg', 'black', 'dark cyan'), # field name background in the search box ('OnFocusBg', 'white', 'dark magenta') # background when a widget is focused ]) urwid.set_encoding('utf8') def main(self): global ui #self.view = ui.run_wrapper(formLayout) self.view = formLayout() self.ui.start() self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_input) self.loop.run() def unhandled_input(self, key): if key == 'f8': quit() return def formLayout(): global ui text1 = urwid.Text("Urwid 3DS Application program - F8 exits.") text2 = urwid.Text("One mission accomplished") textH = urwid.Text("topmost Pile text") cols = urwid.Columns([text1,text2]) pile = urwid.Pile([textH,cols]) fill = urwid.Filler(pile) textT = urwid.Text("Display") textSH = urwid.Text("Pile text in Frame") textF = urwid.Text("Good progress !") frame = urwid.Frame(fill,header=urwid.Pile([textT,textSH]),footer=textF) dim = ui.get_cols_rows() ui.draw_screen(dim, frame.render(dim, True)) return def RandomColor(): '''Pick a random color for the main menu text''' listOfColors = ['dark red', 'dark green', 'brown', 'dark blue', 'dark magenta', 'dark cyan', 'light gray', 'dark gray', 'light red', 'light green', 'yellow', 'light blue', 'light magenta', 'light cyan', 'default'] color = listOfColors[random.randint(0, 14)] return color def main(): form = FormDisplay() form.main() ######################################## ##### MAIN ENTRY POINT ######################################## if __name__ == '__main__': main() ``` I don't want to change the function formLayout as I intend to add more to this basic code framework, where in another function will be added that repeatedly calls formLayout to keep updating the screen based on reading values from a yml file. I already have a separate code that deals with reading the yaml file and extracting ordered dictionaries out it. After figuring out how to get basic urwid console working, I can move on to integrating both to create my final application.
2013/07/28
[ "https://Stackoverflow.com/questions/17903820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534758/" ]
It means that self.\_started has been evaluated to False. ``` assert <Some boolean expression>, "Message if exp is False" ``` If the expression is evaluated to True, nothing special will happen, but if the expression is evaluated to False an AssertionError exception will be thrown. You can try/except the line if you want a cleaner message: ``` try: assert self._started, "The screen is not up and running !" except AssertionError as e: print "Oops, something happened: " + str(e) ``` Some documentation: <http://www.tutorialspoint.com/python/assertions_in_python.htm>
You call `formLayout` before you `start` the screen. `formLayout` calls `ui.draw_screen`, which requires that the screen has been started.
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Thanks for all the answers and comments ! Thought for a while and got another answer in my previous way I have written the code. So, I am posting it. ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] e = d[:] # just a bit of trick/spice >>> for i in d: ... if d.count(i) == 1: ... e.remove(i) ... >>> e [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b'] ``` @arshajii, Your explanation led me to this trick. Thanks !
You can also do like this : ``` data=[1,2,3,4,1,2,3,1,2,1,5,6] first_list=[] second_list=[] for i in data: if data.count(i)==1: first_list.append(i) else: second_list.append(i) print (second_list) ``` Result ====== [1, 2, 3, 1, 2, 3, 1, 2, 1]
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
I just thought I would add my method with set comprehension if anyone was interested. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> d = list({x for x in d if d.count(x) > 1}) >>> print d ['a', 1, 2, 'b', 4] ``` Python 2.7 and up I believe for the set comprehension functionality.
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, 'b', 4] ```
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Thanks for all the answers and comments ! Thought for a while and got another answer in my previous way I have written the code. So, I am posting it. ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] e = d[:] # just a bit of trick/spice >>> for i in d: ... if d.count(i) == 1: ... e.remove(i) ... >>> e [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b'] ``` @arshajii, Your explanation led me to this trick. Thanks !
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, 'b', 4] ```
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Removing elements of a list while iterating over it is never a good idea. The appropriate way to do this would be to use a [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) with a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions): ``` >>> from collections import Counter >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6, 'f', 3] >>> # Use items() instead of iteritems() in Python 3 >>> [k for (k,v) in Counter(d).iteritems() if v > 1] ['a', 1, 2, 'b', 4] ``` If you want keep the duplicate elements in the order in which they appear in your list: ``` >>> keep = {k for (k,v) in Counter(d).iteritems() if v > 1} >>> [x for x in d if x in keep] [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b'] ``` --- I'll try to explain why your approach doesn't work. To understand why some elements aren't removed as they should be, imagine that we want to remove all `b`s from the list `[a, b, b, c]` while looping over it. It'll look something like this: ``` +-----------------------+ | a | b | b | c | +-----------------------+ ^ (first iteration) +-----------------------+ | a | b | b | c | +-----------------------+ ^ (next iteration: we found a 'b' -- remove it) +-----------------------+ | a | | b | c | +-----------------------+ ^ (removed b) +-----------------+ | a | b | c | +-----------------+ ^ (shift subsequent elements down to fill vacancy) +-----------------+ | a | b | c | +-----------------+ ^ (next iteration) ``` Notice that we skipped the second `b`! Once we removed the first `b`, elements were shifted down and our `for`-loop consequently failed to touch every element of the list. The same thing happens in your code.
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, 'b', 4] ```
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Thanks for all the answers and comments ! Thought for a while and got another answer in my previous way I have written the code. So, I am posting it. ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] e = d[:] # just a bit of trick/spice >>> for i in d: ... if d.count(i) == 1: ... e.remove(i) ... >>> e [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b'] ``` @arshajii, Your explanation led me to this trick. Thanks !
For ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] ``` Using conversion to a set yields the unique items: ``` >>> d_unique = list(set(d)) ``` Non-unique items can be found using a list comprehension ``` >>> [item for item in d_unique if d.count(item) >1] [1, 2, 4, 'a', 'b'] ```
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Removing elements of a list while iterating over it is never a good idea. The appropriate way to do this would be to use a [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) with a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions): ``` >>> from collections import Counter >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6, 'f', 3] >>> # Use items() instead of iteritems() in Python 3 >>> [k for (k,v) in Counter(d).iteritems() if v > 1] ['a', 1, 2, 'b', 4] ``` If you want keep the duplicate elements in the order in which they appear in your list: ``` >>> keep = {k for (k,v) in Counter(d).iteritems() if v > 1} >>> [x for x in d if x in keep] [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b'] ``` --- I'll try to explain why your approach doesn't work. To understand why some elements aren't removed as they should be, imagine that we want to remove all `b`s from the list `[a, b, b, c]` while looping over it. It'll look something like this: ``` +-----------------------+ | a | b | b | c | +-----------------------+ ^ (first iteration) +-----------------------+ | a | b | b | c | +-----------------------+ ^ (next iteration: we found a 'b' -- remove it) +-----------------------+ | a | | b | c | +-----------------------+ ^ (removed b) +-----------------+ | a | b | c | +-----------------+ ^ (shift subsequent elements down to fill vacancy) +-----------------+ | a | b | c | +-----------------+ ^ (next iteration) ``` Notice that we skipped the second `b`! Once we removed the first `b`, elements were shifted down and our `for`-loop consequently failed to touch every element of the list. The same thing happens in your code.
I just thought I would add my method with set comprehension if anyone was interested. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> d = list({x for x in d if d.count(x) > 1}) >>> print d ['a', 1, 2, 'b', 4] ``` Python 2.7 and up I believe for the set comprehension functionality.
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Better use [collections.Counter()](http://docs.python.org/2/library/collections.html#counter-objects): ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).iteritems() if v > 1] ['a', 1, 2, 'b', 4] ``` Also see relevant thread: * [How to find duplicate elements in array using for loop in Python?](https://stackoverflow.com/questions/1920145/how-to-find-duplicate-elements-in-array-using-for-loop-in-python-like-c-c)
For ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] ``` Using conversion to a set yields the unique items: ``` >>> d_unique = list(set(d)) ``` Non-unique items can be found using a list comprehension ``` >>> [item for item in d_unique if d.count(item) >1] [1, 2, 4, 'a', 'b'] ```
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Removing elements of a list while iterating over it is never a good idea. The appropriate way to do this would be to use a [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) with a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions): ``` >>> from collections import Counter >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6, 'f', 3] >>> # Use items() instead of iteritems() in Python 3 >>> [k for (k,v) in Counter(d).iteritems() if v > 1] ['a', 1, 2, 'b', 4] ``` If you want keep the duplicate elements in the order in which they appear in your list: ``` >>> keep = {k for (k,v) in Counter(d).iteritems() if v > 1} >>> [x for x in d if x in keep] [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b'] ``` --- I'll try to explain why your approach doesn't work. To understand why some elements aren't removed as they should be, imagine that we want to remove all `b`s from the list `[a, b, b, c]` while looping over it. It'll look something like this: ``` +-----------------------+ | a | b | b | c | +-----------------------+ ^ (first iteration) +-----------------------+ | a | b | b | c | +-----------------------+ ^ (next iteration: we found a 'b' -- remove it) +-----------------------+ | a | | b | c | +-----------------------+ ^ (removed b) +-----------------+ | a | b | c | +-----------------+ ^ (shift subsequent elements down to fill vacancy) +-----------------+ | a | b | c | +-----------------+ ^ (next iteration) ``` Notice that we skipped the second `b`! Once we removed the first `b`, elements were shifted down and our `for`-loop consequently failed to touch every element of the list. The same thing happens in your code.
Thanks for all the answers and comments ! Thought for a while and got another answer in my previous way I have written the code. So, I am posting it. ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] e = d[:] # just a bit of trick/spice >>> for i in d: ... if d.count(i) == 1: ... e.remove(i) ... >>> e [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b'] ``` @arshajii, Your explanation led me to this trick. Thanks !
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
You can also do like this : ``` data=[1,2,3,4,1,2,3,1,2,1,5,6] first_list=[] second_list=[] for i in data: if data.count(i)==1: first_list.append(i) else: second_list.append(i) print (second_list) ``` Result ====== [1, 2, 3, 1, 2, 3, 1, 2, 1]
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, 'b', 4] ```
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', 'a', 'b', 6, 3] ``` 6 and 3 should have been removed. where as, if I use ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c'] ``` I am getting correct answer. Please explain what is happening, I am confused !!! I am using python 2.7.5.
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Better use [collections.Counter()](http://docs.python.org/2/library/collections.html#counter-objects): ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).iteritems() if v > 1] ['a', 1, 2, 'b', 4] ``` Also see relevant thread: * [How to find duplicate elements in array using for loop in Python?](https://stackoverflow.com/questions/1920145/how-to-find-duplicate-elements-in-array-using-for-loop-in-python-like-c-c)
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, 'b', 4] ```
15,000,311
I am having trouble to start a python script and get the parameters I send to the script. ![enter image description here](https://i.stack.imgur.com/z2Pnj.jpg) As you can see if I start the following test script with python comand, it works, if not, well, no arguments are passed to the script :/ ``` import optparse import sys oOptParse = optparse.OptionParser() oOptParse.add_option("--arg", dest="arg", help="Test param") oOptParse.set_default("arg", None) if len(sys.argv) == 1: oOptParse.print_help( ) sys.exit( 1 ) aOptions = oOptParse.parse_args( ) oOptions = aOptions[0] print (oOptions.arg) ``` Do you have any idea what could be the problem ? Thanks a lot !
2013/02/21
[ "https://Stackoverflow.com/questions/15000311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095037/" ]
Check out [ImageResizer](http://imageresizing.net) - it's a suite of NuGet packages designed for this exact purpose. It runs eBay in Denmark, MSN Olympics, and a few other big sites. Dynamic image processing can be done safely and efficiently, but not in a sane amount of code. It's [trickier than it appears](http://www.nathanaeljones.com/blog/2009/20-image-resizing-pitfalls).
I wouldn't recommend this but you can do next thing: ``` using (Image img = Image.FromStream(originalImage)) { using (Bitmap bitmap = new Bitmap(img, width, height)) { bitmap.Save(outputStream, ImageFormat.Jpeg); } } ``` Be aware that this could cause OutOfMemoryException.
14,486,802
What are common uses for Python's built-in `coerce` function? I can see applying it if I do not know the `type` of a numeric value [as per the documentation](http://docs.python.org/2/library/functions.html#coerce), but do other common usages exist? I would guess that `coerce()` is also called when performing arithmetic computations, *e.g.* `x = 1.0 +2`. It's a built-in function, so presumably it has some potential common usage?
2013/01/23
[ "https://Stackoverflow.com/questions/14486802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/839375/" ]
Its a left over from [early python](http://docs.python.org/release/1.5.2/ref/numeric-types.html), it basically makes a tuple of numbers to be the same underlying number type e.g. ``` >>> type(10) <type 'int'> >>> type(10.0101010) <type 'float'> >>> nums = coerce(10, 10.001010) >>> type(nums[0]) <type 'float'> >>> type(nums[1]) <type 'float'> ``` It is also to allow objects to act like numbers with old classes (a bad example of its usage here would be ...) ``` >>> class bad: ... """ Dont do this, even if coerce was a good idea this simply ... makes itself int ignoring type of other ! """ ... def __init__(self, s): ... self.s = s ... def __coerce__(self, other): ... return (other, int(self.s)) ... >>> coerce(10, bad("102")) (102, 10) ```
Python core programing says: > > Function coerce () provides the programmer do not rely on the Python interpreter, but custom two numerical type conversion." > > > e.g. ``` >>> coerce(1, 2) (1, 2) >>> >>> coerce(1.3, 134L) (1.3, 134.0) >>> >>> coerce(1, 134L) (1L, 134L) >>> >>> coerce(1j, 134L) (1j, (134+0j)) >>> >>> coerce(1.23-41j, 134L) ((1.23-41j), (134+0j)) ```
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $ ps axf 26077 pts/12 Ss 0:00 \_ -bash 4189 pts/12 S+ 0:00 | \_ python manage.py runserver 4194 pts/12 Sl+ 0:00 | \_ /myproject/.virtualenv/bin/python manage.py runserver $ kill -s SIGINT 4189 $ ps axf 4194 pts/12 Sl 0:00 /sh/myproject/.virtualenv/bin/python manage.py runserver ``` My understanding is that SIGINT should emulate pressing Ctrl-C in the terminal, but notice that SIGINT terminates the parent, 4189, but not the child, 4194. Same behavior for SIGKILL, SIGTERM, SIGSTOP. Using Ctrl-C from the terminal kills both as expected. Is there a way to terminate the parent in a way that also kills the child without knowing the child's PID?
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
Put a dash in front of the process, this should kill the process group. ``` kill -s SIGINT -4189 ```
`kill -9 4189` Have a try, it should work!
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $ ps axf 26077 pts/12 Ss 0:00 \_ -bash 4189 pts/12 S+ 0:00 | \_ python manage.py runserver 4194 pts/12 Sl+ 0:00 | \_ /myproject/.virtualenv/bin/python manage.py runserver $ kill -s SIGINT 4189 $ ps axf 4194 pts/12 Sl 0:00 /sh/myproject/.virtualenv/bin/python manage.py runserver ``` My understanding is that SIGINT should emulate pressing Ctrl-C in the terminal, but notice that SIGINT terminates the parent, 4189, but not the child, 4194. Same behavior for SIGKILL, SIGTERM, SIGSTOP. Using Ctrl-C from the terminal kills both as expected. Is there a way to terminate the parent in a way that also kills the child without knowing the child's PID?
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
`kill -9 4189` Have a try, it should work!
I had similar problem but accepted answer didn't work on my CentOS: ``` $ ps fx | grep [p]ython 30864 pts/0 S 0:00 python manage.py runserver 0.0.0.0:80 30866 pts/0 Sl 0:00 \_ /var/webapp/venv/bin/python manage.py runserver 0.0.0.0:80 $ kill -s SIGINT -30864 -bash: kill: 30864: invalid signal specification ``` So, I found this solution: ``` $ pkill -P 30864 $ ps fx | grep [p]ython $ # empty ```
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $ ps axf 26077 pts/12 Ss 0:00 \_ -bash 4189 pts/12 S+ 0:00 | \_ python manage.py runserver 4194 pts/12 Sl+ 0:00 | \_ /myproject/.virtualenv/bin/python manage.py runserver $ kill -s SIGINT 4189 $ ps axf 4194 pts/12 Sl 0:00 /sh/myproject/.virtualenv/bin/python manage.py runserver ``` My understanding is that SIGINT should emulate pressing Ctrl-C in the terminal, but notice that SIGINT terminates the parent, 4189, but not the child, 4194. Same behavior for SIGKILL, SIGTERM, SIGSTOP. Using Ctrl-C from the terminal kills both as expected. Is there a way to terminate the parent in a way that also kills the child without knowing the child's PID?
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
`kill -9 4189` Have a try, it should work!
Try using `pkill`: ``` $ pkill -f "python3 manage.py runserver" ```
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $ ps axf 26077 pts/12 Ss 0:00 \_ -bash 4189 pts/12 S+ 0:00 | \_ python manage.py runserver 4194 pts/12 Sl+ 0:00 | \_ /myproject/.virtualenv/bin/python manage.py runserver $ kill -s SIGINT 4189 $ ps axf 4194 pts/12 Sl 0:00 /sh/myproject/.virtualenv/bin/python manage.py runserver ``` My understanding is that SIGINT should emulate pressing Ctrl-C in the terminal, but notice that SIGINT terminates the parent, 4189, but not the child, 4194. Same behavior for SIGKILL, SIGTERM, SIGSTOP. Using Ctrl-C from the terminal kills both as expected. Is there a way to terminate the parent in a way that also kills the child without knowing the child's PID?
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
Put a dash in front of the process, this should kill the process group. ``` kill -s SIGINT -4189 ```
I had similar problem but accepted answer didn't work on my CentOS: ``` $ ps fx | grep [p]ython 30864 pts/0 S 0:00 python manage.py runserver 0.0.0.0:80 30866 pts/0 Sl 0:00 \_ /var/webapp/venv/bin/python manage.py runserver 0.0.0.0:80 $ kill -s SIGINT -30864 -bash: kill: 30864: invalid signal specification ``` So, I found this solution: ``` $ pkill -P 30864 $ ps fx | grep [p]ython $ # empty ```
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $ ps axf 26077 pts/12 Ss 0:00 \_ -bash 4189 pts/12 S+ 0:00 | \_ python manage.py runserver 4194 pts/12 Sl+ 0:00 | \_ /myproject/.virtualenv/bin/python manage.py runserver $ kill -s SIGINT 4189 $ ps axf 4194 pts/12 Sl 0:00 /sh/myproject/.virtualenv/bin/python manage.py runserver ``` My understanding is that SIGINT should emulate pressing Ctrl-C in the terminal, but notice that SIGINT terminates the parent, 4189, but not the child, 4194. Same behavior for SIGKILL, SIGTERM, SIGSTOP. Using Ctrl-C from the terminal kills both as expected. Is there a way to terminate the parent in a way that also kills the child without knowing the child's PID?
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
Put a dash in front of the process, this should kill the process group. ``` kill -s SIGINT -4189 ```
Try using `pkill`: ``` $ pkill -f "python3 manage.py runserver" ```
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $ ps axf 26077 pts/12 Ss 0:00 \_ -bash 4189 pts/12 S+ 0:00 | \_ python manage.py runserver 4194 pts/12 Sl+ 0:00 | \_ /myproject/.virtualenv/bin/python manage.py runserver $ kill -s SIGINT 4189 $ ps axf 4194 pts/12 Sl 0:00 /sh/myproject/.virtualenv/bin/python manage.py runserver ``` My understanding is that SIGINT should emulate pressing Ctrl-C in the terminal, but notice that SIGINT terminates the parent, 4189, but not the child, 4194. Same behavior for SIGKILL, SIGTERM, SIGSTOP. Using Ctrl-C from the terminal kills both as expected. Is there a way to terminate the parent in a way that also kills the child without knowing the child's PID?
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
I had similar problem but accepted answer didn't work on my CentOS: ``` $ ps fx | grep [p]ython 30864 pts/0 S 0:00 python manage.py runserver 0.0.0.0:80 30866 pts/0 Sl 0:00 \_ /var/webapp/venv/bin/python manage.py runserver 0.0.0.0:80 $ kill -s SIGINT -30864 -bash: kill: 30864: invalid signal specification ``` So, I found this solution: ``` $ pkill -P 30864 $ ps fx | grep [p]ython $ # empty ```
Try using `pkill`: ``` $ pkill -f "python3 manage.py runserver" ```
11,941,027
Python beginner here. I have two text files with the same format of tab-delimited information. They contain rows with 3 columns (identifier, chromosome and position) eg: File 1: ``` 2323 2 125 2324 3 754 ``` ... etc File 2: ``` 2323 2 150 2324 3 12000 ``` ... etc I want to create a list or matrix (not sure exactly what is best or how this works, maybe a list of lists that becomes a matrix?!) by going through each identifier (the first column in each row) in one file and associate it with its position (column3), then find this matching identifier in the next file and also save the other position (column3) in this file. SO in the end each identifier will be associated with 2 different positions from the two different files. This is what I need help with. For the next step I will look for identifiers with the largest numerical difference between positions. Any help, tips or solutions are greatly appreciated, I am a python beginner with a very basic knowledge. Many thanks in advance! Rubal
2012/08/13
[ "https://Stackoverflow.com/questions/11941027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/964689/" ]
There can be several answers to your question: 1. If you plan to use extensive computations with matrices, I advice you to look at [numpy](http://numpy.scipy.org/) library that is very efficient. You can see how to create matrices with numpy [here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html). 2. The second possible answer to your question is to use [biopython](http://biopython.org/wiki/Main_Page) library (I've made conclusion about that you're working with chromosomes). 3. You can use Python nested lists to create matrices. Here's a code snippet of how to do that (assuming we're reading from File 2) ``` matrix = [] with open(path_to_file2, 'rt') as f: for line in f: matrix.append(map(int, line.strip().split(' '))) ``` You can then get values of the created matrix: ``` matrix[0] # First row == [2323, 2, 150] matrix[0][1] # Second column, first row == 2 ```
You could use a dictionary having the identifier as the key and a list of the positions as the value. Then you can calculate the difference between the positions and have it as the 3rd element of the list. You can then iterate through the dictionary finding the largest value in position [2] of the dictionary's values. ``` d = {} for each line in file1: d[identifier] = [position] for each line in file2: d[identifier].append(position) d[identifier].append(d[identifier][1]-d[identifier][0]) maxDiff = 0 for x in d: value = d[x][2] if value > maxDiff: maxDiff = value ```
11,941,027
Python beginner here. I have two text files with the same format of tab-delimited information. They contain rows with 3 columns (identifier, chromosome and position) eg: File 1: ``` 2323 2 125 2324 3 754 ``` ... etc File 2: ``` 2323 2 150 2324 3 12000 ``` ... etc I want to create a list or matrix (not sure exactly what is best or how this works, maybe a list of lists that becomes a matrix?!) by going through each identifier (the first column in each row) in one file and associate it with its position (column3), then find this matching identifier in the next file and also save the other position (column3) in this file. SO in the end each identifier will be associated with 2 different positions from the two different files. This is what I need help with. For the next step I will look for identifiers with the largest numerical difference between positions. Any help, tips or solutions are greatly appreciated, I am a python beginner with a very basic knowledge. Many thanks in advance! Rubal
2012/08/13
[ "https://Stackoverflow.com/questions/11941027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/964689/" ]
``` import collections d=collections.defaultdict(list) for f in ('file1','file2'): with open(f) as f1: for line in f1: ident, chrom, pos = line.split() d[ident].append(int( pos )) #big differences at end of list items = sorted(d.items(), key = lambda item: abs(item[1][1] - item[1][0])) #big differences at beginning of list #items = sorted(d.items(), reverse = True, key = lambda item: abs(item[1][1] - item[1][0])) ``` In this solution, I store the information from the files as a dictionary. the keys are the identifier and the values are a list containing the positions. I then sort the items of that dictionary based on the absolute value of the difference between the first and second element in the list of positions. In other words, the biggest differences are at the end of the `items` list. In order for this to work, it assumes that `file1` and `file2` have *the same identifiers*. If they don't, you'll first need to filter the items to pick out only dictionary entries with values that have a length of 2. e.g. ``` items = [(k,v) for k,v in d.items() if len(v) == 2] items = sorted(items, ...) ```
You could use a dictionary having the identifier as the key and a list of the positions as the value. Then you can calculate the difference between the positions and have it as the 3rd element of the list. You can then iterate through the dictionary finding the largest value in position [2] of the dictionary's values. ``` d = {} for each line in file1: d[identifier] = [position] for each line in file2: d[identifier].append(position) d[identifier].append(d[identifier][1]-d[identifier][0]) maxDiff = 0 for x in d: value = d[x][2] if value > maxDiff: maxDiff = value ```
61,232,982
This is my code: ``` users.age.mean().astype(int64) ``` (where users is the name of dataframe and age is a column in it) This is the error I am getting: ``` AttributeError Traceback (most recent call last) <ipython-input-29-10b672e7f7ae> in <module> ----> 1 users.age.mean().astype(int64) AttributeError: 'float' object has no attribute 'astype' ```
2020/04/15
[ "https://Stackoverflow.com/questions/61232982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13322571/" ]
`users.age.mean()` returns a float not a series. Floats don't have `astype`, only pandas series. Try: `x = numpy.int64(users.age.mean())` Or: `x = int(users.age.mean())`
Try `int` before your function example: ``` X = int(users.age.mean()) ``` Hope it helps!
997,419
Is there any lib available to connect to yahoo messenger using either the standard protocol or the http way from python?
2009/06/15
[ "https://Stackoverflow.com/questions/997419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9789/" ]
Google is your friend. The [Python Package Index](http://pypi.python.org/pypi) has [several](http://pypi.python.org/pypi?%3Aaction=search&term=yahoo&submit=search) modules to do with Yahoo, including this [one](http://pypi.python.org/pypi/pyahoolib/0.2) which matches your requirements.
There is also the [Yahoo IM SDK](http://developer.yahoo.com/messenger/guide/index.html) that might help.
5,342,359
is it possible to Insert a python tuple in a postgresql database
2011/03/17
[ "https://Stackoverflow.com/questions/5342359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654796/" ]
Yes it is, PostgreSQL supports array as column type. ``` CREATE TABLE tuples_table ( tuple_of_strings text[], tuple_of_ints integer[] ); ``` Then inserting is done like this: ``` INSERT INTO tuples_table VALUES ( ('{"a","b","c"}', '{1,2}'), ('{"e",'f... etc"}', '{3,4,5}') ); ```
Really we need more information. What data is **inside** the tuple? Is it just integers? Just strings? Is it megabytes of images? If you had a Python tuple like `(4,6,2,"Hello",7)` you could insert **the string** `'(4,6,2,"Hello",7)'` into a Postgres database, but that's probably not the answer you're looking for. You really need to figure out what data you're really trying to store before you can figure out how/where to store it. --- **EDIT:** So the short answer is "no", you cannot store an ***arbitrary*** Python tuple in a postgres database, but there's probably some way to take whatever is *inside* the tuple and store it somewhere useful.
5,342,359
is it possible to Insert a python tuple in a postgresql database
2011/03/17
[ "https://Stackoverflow.com/questions/5342359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654796/" ]
Yes, it is. Probably the easiest way is to serialise it using e.g. [marshal](http://docs.python.org/library/marshal.html), [pickle](http://docs.python.org/library/pickle.html) or [json](http://docs.python.org/library/json.html) and store it in a `text` field. Another approach is to use Postgres' multitude of [data types](http://www.postgresql.org/docs/9.0/interactive/datatype.html) e.g. [array type](http://www.postgresql.org/docs/9.0/interactive/arrays.html). Finally, if the number of elements and their types of each tuple is fixed, then you may just create this many columns and map each element to table column.
Really we need more information. What data is **inside** the tuple? Is it just integers? Just strings? Is it megabytes of images? If you had a Python tuple like `(4,6,2,"Hello",7)` you could insert **the string** `'(4,6,2,"Hello",7)'` into a Postgres database, but that's probably not the answer you're looking for. You really need to figure out what data you're really trying to store before you can figure out how/where to store it. --- **EDIT:** So the short answer is "no", you cannot store an ***arbitrary*** Python tuple in a postgres database, but there's probably some way to take whatever is *inside* the tuple and store it somewhere useful.
5,342,359
is it possible to Insert a python tuple in a postgresql database
2011/03/17
[ "https://Stackoverflow.com/questions/5342359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654796/" ]
Yes it is, PostgreSQL supports array as column type. ``` CREATE TABLE tuples_table ( tuple_of_strings text[], tuple_of_ints integer[] ); ``` Then inserting is done like this: ``` INSERT INTO tuples_table VALUES ( ('{"a","b","c"}', '{1,2}'), ('{"e",'f... etc"}', '{3,4,5}') ); ```
This question does not make any sense. You can insert using SQL whatever is supported by your database model. If you need a fancy mapper: look at an ORM like SQLAlchemy.
5,342,359
is it possible to Insert a python tuple in a postgresql database
2011/03/17
[ "https://Stackoverflow.com/questions/5342359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654796/" ]
Yes, it is. Probably the easiest way is to serialise it using e.g. [marshal](http://docs.python.org/library/marshal.html), [pickle](http://docs.python.org/library/pickle.html) or [json](http://docs.python.org/library/json.html) and store it in a `text` field. Another approach is to use Postgres' multitude of [data types](http://www.postgresql.org/docs/9.0/interactive/datatype.html) e.g. [array type](http://www.postgresql.org/docs/9.0/interactive/arrays.html). Finally, if the number of elements and their types of each tuple is fixed, then you may just create this many columns and map each element to table column.
This question does not make any sense. You can insert using SQL whatever is supported by your database model. If you need a fancy mapper: look at an ORM like SQLAlchemy.
65,764,302
I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input. My code looks like this, mind you I am new to all this. ``` print('Please enter a number:') def numberCheck(c): if c % 2 == 0: print(c // 2) elif c % 2 == 1: print(3 * c + 1) c = int(input()) numberCheck(c) ``` I want it to print "Please enter a number" only once. but after running I want it to wait for another number. How would I do this? I tried a `for` loop but that uses a range and I don't want to set a range unless there is a way to do it to infinity.
2021/01/17
[ "https://Stackoverflow.com/questions/65764302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15025453/" ]
So my understanding is you want the function to run indefinitely. this is my approach, through the use of a while loop ``` print("Enter a number") while True: c = int(input("")) numberCheck(c) ```
You could use a `while` loop with `True`: ```py while True: c = int(input()) numberCheck(c) ```
65,764,302
I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input. My code looks like this, mind you I am new to all this. ``` print('Please enter a number:') def numberCheck(c): if c % 2 == 0: print(c // 2) elif c % 2 == 1: print(3 * c + 1) c = int(input()) numberCheck(c) ``` I want it to print "Please enter a number" only once. but after running I want it to wait for another number. How would I do this? I tried a `for` loop but that uses a range and I don't want to set a range unless there is a way to do it to infinity.
2021/01/17
[ "https://Stackoverflow.com/questions/65764302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15025453/" ]
If you want to run an infinite loop, that can be done with a while loop. ``` print('Please enter a number:') def numberCheck(c): if c % 2 == 0: print(c // 2) elif c % 2 == 1: print(3 * c + 1) while True: c = int(input()) numberCheck(c) ```
So my understanding is you want the function to run indefinitely. this is my approach, through the use of a while loop ``` print("Enter a number") while True: c = int(input("")) numberCheck(c) ```
65,764,302
I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input. My code looks like this, mind you I am new to all this. ``` print('Please enter a number:') def numberCheck(c): if c % 2 == 0: print(c // 2) elif c % 2 == 1: print(3 * c + 1) c = int(input()) numberCheck(c) ``` I want it to print "Please enter a number" only once. but after running I want it to wait for another number. How would I do this? I tried a `for` loop but that uses a range and I don't want to set a range unless there is a way to do it to infinity.
2021/01/17
[ "https://Stackoverflow.com/questions/65764302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15025453/" ]
If you want to run an infinite loop, that can be done with a while loop. ``` print('Please enter a number:') def numberCheck(c): if c % 2 == 0: print(c // 2) elif c % 2 == 1: print(3 * c + 1) while True: c = int(input()) numberCheck(c) ```
You could use a `while` loop with `True`: ```py while True: c = int(input()) numberCheck(c) ```
2,341,972
I'm writing a basic html-proxy in python (3), and up to now I'm not using prebuild classes like http.server. I'm just starting a socket which accepts connection: ``` self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_socket.bind((socket.gethostname(), 4321)) self.listen_socket.listen(5) (a, b) = self.listen_socket.accept() content = a.recv(100000) ``` Now content stores data like: ``` b'GET http://www.google.com/firefox HTTP/1.1\r\nHost: www.google.com\r\nUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2) Gecko/20100207 Namoroka/3.6\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\nKeep-Alive: 115\r\nProxy-Connection: keep-alive\r\nCookie: PREF=ID=1ac935f4d893f655:U=73a4849dc5fc23a4:TM=1266851688:LM=1267023171:S=Log1PmXRMlNjX3Of; NID=32=EnrZjTqILuW2_aMLtgsJ96FdEMF3s5FoMJSVq9GMr9dhLhTAd3F5RcQ3ImyVBiO2eYNKKMhzlGg7r8zXmeSq50EigS5sdKtCL9BMHpgCxZazA2NiyB0bTRWhp8-0BObn\r\n\r\n' ``` How can I regexp it? Converting to string does not work for me. Or, eventually, I need to find out the address which is inquired, like `http://www.google.com/firefox` in this case. Is there a parser that I do not know? How can I achieve the result? Thanks in advance.
2010/02/26
[ "https://Stackoverflow.com/questions/2341972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258267/" ]
You need to include an encoding when converting to a string, for example use: ``` >>> str(b'GET http://...', 'UTF-8') 'GET http://...' ``` If you don't use an encoding then as you've discovered you get something a little less helpful: ``` >>> str(b'GET http://...') "b'GET http://...'" ```
Also, you might want to check the `*HTTPServer` classes. They provide a wrapper around being HTTP servers and will also parse headers for you. If you can't, well, at the very least they will provide source code examples on how to do it!
2,341,972
I'm writing a basic html-proxy in python (3), and up to now I'm not using prebuild classes like http.server. I'm just starting a socket which accepts connection: ``` self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_socket.bind((socket.gethostname(), 4321)) self.listen_socket.listen(5) (a, b) = self.listen_socket.accept() content = a.recv(100000) ``` Now content stores data like: ``` b'GET http://www.google.com/firefox HTTP/1.1\r\nHost: www.google.com\r\nUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2) Gecko/20100207 Namoroka/3.6\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\nKeep-Alive: 115\r\nProxy-Connection: keep-alive\r\nCookie: PREF=ID=1ac935f4d893f655:U=73a4849dc5fc23a4:TM=1266851688:LM=1267023171:S=Log1PmXRMlNjX3Of; NID=32=EnrZjTqILuW2_aMLtgsJ96FdEMF3s5FoMJSVq9GMr9dhLhTAd3F5RcQ3ImyVBiO2eYNKKMhzlGg7r8zXmeSq50EigS5sdKtCL9BMHpgCxZazA2NiyB0bTRWhp8-0BObn\r\n\r\n' ``` How can I regexp it? Converting to string does not work for me. Or, eventually, I need to find out the address which is inquired, like `http://www.google.com/firefox` in this case. Is there a parser that I do not know? How can I achieve the result? Thanks in advance.
2010/02/26
[ "https://Stackoverflow.com/questions/2341972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258267/" ]
You need to include an encoding when converting to a string, for example use: ``` >>> str(b'GET http://...', 'UTF-8') 'GET http://...' ``` If you don't use an encoding then as you've discovered you get something a little less helpful: ``` >>> str(b'GET http://...') "b'GET http://...'" ```
Methods are provided to convert between bytes and strings try str.encode() and bytes.decode() <http://python.about.com/od/python30/ss/30_strings_3.htm>
2,341,972
I'm writing a basic html-proxy in python (3), and up to now I'm not using prebuild classes like http.server. I'm just starting a socket which accepts connection: ``` self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_socket.bind((socket.gethostname(), 4321)) self.listen_socket.listen(5) (a, b) = self.listen_socket.accept() content = a.recv(100000) ``` Now content stores data like: ``` b'GET http://www.google.com/firefox HTTP/1.1\r\nHost: www.google.com\r\nUser-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2) Gecko/20100207 Namoroka/3.6\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: en-us,en;q=0.5\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\nKeep-Alive: 115\r\nProxy-Connection: keep-alive\r\nCookie: PREF=ID=1ac935f4d893f655:U=73a4849dc5fc23a4:TM=1266851688:LM=1267023171:S=Log1PmXRMlNjX3Of; NID=32=EnrZjTqILuW2_aMLtgsJ96FdEMF3s5FoMJSVq9GMr9dhLhTAd3F5RcQ3ImyVBiO2eYNKKMhzlGg7r8zXmeSq50EigS5sdKtCL9BMHpgCxZazA2NiyB0bTRWhp8-0BObn\r\n\r\n' ``` How can I regexp it? Converting to string does not work for me. Or, eventually, I need to find out the address which is inquired, like `http://www.google.com/firefox` in this case. Is there a parser that I do not know? How can I achieve the result? Thanks in advance.
2010/02/26
[ "https://Stackoverflow.com/questions/2341972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258267/" ]
Also, you might want to check the `*HTTPServer` classes. They provide a wrapper around being HTTP servers and will also parse headers for you. If you can't, well, at the very least they will provide source code examples on how to do it!
Methods are provided to convert between bytes and strings try str.encode() and bytes.decode() <http://python.about.com/od/python30/ss/30_strings_3.htm>
19,806,494
I'm attempting to write a cython interface to the complex version of the MUMPS solver (zmumps). I'm running into some problems as I have no previous experience with either C or cython. Following the example of the [pymumps package](https://github.com/bfroehle/pymumps) I was able to get the real version of the code (dmumps) to work. I believe that my problem are the pointers to the ZMUMPS\_COMPLEX structures. For the So far I have the following (lifted heavily from [pymumps](https://github.com/bfroehle/pymumps)): **zmumps\_c.pxd:** ``` from libc.string cimport strncpy cdef extern from "mumps_c_types.h": ctypedef struct ZMUMPS_COMPLEX "ZMUMPS_COMPLEX": double r double i cdef extern from "zmumps_c.h": ctypedef int MUMPS_INT ctypedef struct c_ZMUMPS_STRUC_C "ZMUMPS_STRUC_C": MUMPS_INT sym, par, job MUMPS_INT comm_fortran # Fortran communicator MUMPS_INT n # Assembled entry MUMPS_INT nz MUMPS_INT *irn MUMPS_INT *jcn ZMUMPS_COMPLEX *a # RHS and statistics ZMUMPS_COMPLEX *rhs MUMPS_INT infog[40] void c_zmumps_c "zmumps_c" (c_ZMUMPS_STRUC_C *) ``` **zmumps\_c.pyx** ``` cdef class ZMUMPS_STRUC_C: cdef c_ZMUMPS_STRUC_C ob property sym: def __get__(self): return self.ob.sym def __set__(self, value): self.ob.sym = value property par: def __get__(self): return self.ob.par def __set__(self, value): self.ob.par = value property job: def __get__(self): return self.ob.job def __set__(self, value): self.ob.job = value property comm_fortran: def __get__(self): return self.ob.comm_fortran def __set__(self, value): self.ob.comm_fortran = value property n: def __get__(self): return self.ob.n def __set__(self, value): self.ob.n = value property nz: def __get__(self): return self.ob.nz def __set__(self, value): self.ob.nz = value property irn: def __get__(self): return <long> self.ob.irn def __set__(self, long value): self.ob.irn = <MUMPS_INT*> value property jcn: def __get__(self): return <long> self.ob.jcn def __set__(self, long value): self.ob.jcn = <MUMPS_INT*> value property a: def __get__(self): return <long> self.ob.a def __set__(self, long value): self.ob.a = <ZMUMPS_COMPLEX*> value property rhs: def __get__(self): return <long> self.ob.rhs def __set__(self, long value): self.ob.rhs = <ZMUMPS_COMPLEX*> value property infog: def __get__(self): cdef MUMPS_INT[:] view = self.ob.infog return view def zmumps_c(ZMUMPS_STRUC_C s not None): c_zmumps_c(&s.ob) ``` In my python code I'm able to set the irn and jcn using ``` import zmumps_c import numpy as np MUMPS_STRUC_C = staticmethod(zmumps_c.ZMUMPS_STRUC_C) id = MUMPS_STRUC_C() x = np.r_[1:10] id.irn = x.__array_interface__['data'][0] ``` However, I have no idea how to set the values of a or rhs. Any help would be greatly appreciated.
2013/11/06
[ "https://Stackoverflow.com/questions/19806494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2661958/" ]
Form a user standpoint hovering 1 cm over the screens highly inconvenient compared to placing a finger over the screen. Swipes seen by a front facing camera with a small aperture will be contaminated with the motion blur for a reasonable speed of swipe. A few years back I solved this problem by considering how motion blur of swipe would eventually occlude the image on the background. In particular, if background has some gradient, it will be erased by the motion blur of the moving hand. Thus if you histogram vertical gradient, you will see a hole moving through your histogram when you swipe and the direction of motion of this hole is your swipe direction. Two more pointers: if there is not much gradient on the background one can simply reduce image resolution and work with the gradient image of the hand that is less affected by the motion blur at lower resolutions. When camera itself moves the edge histogram will translate globally as opposed to a hole moving through a histogram. Finally, extreme phone rotations can be detected by embeded gyroscope to avoid false positives.
You can't detect the motion vector with the proximity sensor. But there usually is a much smarter sensor that allows for much more precision: the front camera. It is more complex to read gestures with a camera, but you can definitely do that with OpenCV, for example.
50,242,147
It's easy in python to calculate simple permutations using [itertools.permutations()](https://docs.python.org/3/library/itertools.html#itertools.permutations). You can even find some [possible permutations of multiple lists](https://stackoverflow.com/q/2853212). ``` import itertools s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ] for l in list(itertools.product(*s)): print(l) ('a', 'd', 'e') ('a', 'd', 'f') ('b', 'd', 'e') ('b', 'd', 'f') ('c', 'd', 'e') ('c', 'd', 'f') ``` It's also possible to find [permutations of different lengths](https://stackoverflow.com/a/5898031/99923). ``` import itertools s = [1, 2, 3] for L in range(0, len(s)+1): for subset in itertools.combinations(s, L): print(subset) () (1,) (2,) (3,) (1, 2) (1, 3) (2, 3) (1, 2, 3) ``` How would you find permutations of all possible 1) **lengths**, 2) **orders**, and 3) from **multiple lists**? I would assume the first step would be to combine the lists into one. A list will not de-dup items like a set would. ``` s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ] ('a', 'b') ('a', 'c') ('a', 'd') ('a', 'e') ('a', 'f') ... ('b', 'a') ('c', 'a') ... ('a', 'b', 'c', 'd', 'e') ... ('a', 'b', 'c', 'd', 'e', 'f') ... ('f', 'a', 'b', 'c', 'd', 'e') ```
2018/05/08
[ "https://Stackoverflow.com/questions/50242147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99923/" ]
Like you suggested, do: ``` s = [x for y in s for x in y] ``` and then use your solution for finding permutations of different lengths: ``` for L in range(0, len(s)+1): for subset in itertools.combinations(s, L): print(subset) ``` would find: ``` () ('a',) ('b',) ('c',) ('d',) ('e',) ('f',) ('a', 'b') ('a', 'c') ('a', 'd') ('a', 'e') ('a', 'f') ('b', 'c') ('b', 'd') ('b', 'e') ('b', 'f') ('c', 'd') ('c', 'e') ('c', 'f') ('d', 'e') ('d', 'f') ('e', 'f') ('a', 'b', 'c') ('a', 'b', 'd') ('a', 'b', 'e') ('a', 'b', 'f') ('a', 'c', 'd') ('a', 'c', 'e') ('a', 'c', 'f') ('a', 'd', 'e') ('a', 'd', 'f') ('a', 'e', 'f') ('b', 'c', 'd') ('b', 'c', 'e') ('b', 'c', 'f') ('b', 'd', 'e') ('b', 'd', 'f') ('b', 'e', 'f') ('c', 'd', 'e') ('c', 'd', 'f') ('c', 'e', 'f') ('d', 'e', 'f') ('a', 'b', 'c', 'd') ('a', 'b', 'c', 'e') ('a', 'b', 'c', 'f') ('a', 'b', 'd', 'e') ('a', 'b', 'd', 'f') ('a', 'b', 'e', 'f') ('a', 'c', 'd', 'e') ('a', 'c', 'd', 'f') ('a', 'c', 'e', 'f') ('a', 'd', 'e', 'f') ('b', 'c', 'd', 'e') ('b', 'c', 'd', 'f') ('b', 'c', 'e', 'f') ('b', 'd', 'e', 'f') ('c', 'd', 'e', 'f') ('a', 'b', 'c', 'd', 'e') ('a', 'b', 'c', 'd', 'f') ('a', 'b', 'c', 'e', 'f') ('a', 'b', 'd', 'e', 'f') ('a', 'c', 'd', 'e', 'f') ('b', 'c', 'd', 'e', 'f') ('a', 'b', 'c', 'd', 'e', 'f') ``` If you want to distinguish e.g. `('d', 'e', 'f')` from `('f', 'e', 'd')` (thanks [@Kefeng91](https://stackoverflow.com/users/9729313/kefeng91) for pointing this out) and others, replace `itertools.combinations` with `itertools.permutations`, like [@YakymPirozhenko](https://stackoverflow.com/users/4585963/yakym-pirozhenko) suggests.
Here's a simple one liner (You can replace `feature_cols` instead of `s`) **Combinations:** ```py [combo for i in range(1, len(feature_cols) + 1) for combo in itertools.combinations(feature_cols, i) ] ``` **Permutations:** ```py [combo for i in range(1, len(feature_cols) + 1) for combo in itertools.permutations(feature_cols, i) ] ``` See [my answer here](https://stackoverflow.com/a/68694374/8751871) for more details
63,096,451
I am pretty good at python and couldn't figure out how to use the Mojang API with python. I want to d something like `GET https://api.mojang.com/users/profiles/minecraft/<username>?at=<timestamp>`(from the API) but I can't figure out how to do it! Does anyone know how to do this? I'm in python 3.8. <https://wiki.vg/Mojang_API#Username_-.3E_UUID_at_time>
2020/07/26
[ "https://Stackoverflow.com/questions/63096451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13996262/" ]
It's pretty straightforward, just replace `<username>` with the person's username, and the response will give your their `uuid`. Here is an example using **[`requests`](https://2.python-requests.org/en/master/)**: ``` import requests username = 'KrisJelbring' url = f'https://api.mojang.com/users/profiles/minecraft/{username}?' response = requests.get(url) uuid = response.json()['id'] print(uuid) #7125ba8b1c864508b92bb5c042ccfe2b ```
The documentation is relatively straightforward. You want to send a `GET` request with their username: ```py import requests username = "Bob" resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{username}") uuid = resp.json()["id"] print(f"Bob's current UUID is {uuid}") ``` Optionally, you can include a UNIX timestamp to get the username's UUID at a specific point in time: ```py username = "Alice" # UNIX timestamp that equates to 01/01/2018 timestamp = 1514764800 resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{username}?at={timestamp}") uuid = resp.json()["id"] print(f"Alice's UUID on 01/01/2018 was {uuid}") ``` Other Solution (third party library) ------------------------------------ Alternatively, you can use my newly released [Mojang package](https://github.com/summer/mojang), if you don't want to deal with the HTTP requests, JSON, and other web junk in your code. Install it with pip by running the following console command: ``` python -m pip install mojang ``` Usage: ```py from mojang import API api = API() uuid = api.get_uuid("Alice") print(f"Alice's UUID is {uuid}") # or with a timestamp uuid = api.get_uuid("Alice", timestamp=1514764800) print(f"Alice's UUID on 01/01/2018 was {uuid}") ```
63,096,451
I am pretty good at python and couldn't figure out how to use the Mojang API with python. I want to d something like `GET https://api.mojang.com/users/profiles/minecraft/<username>?at=<timestamp>`(from the API) but I can't figure out how to do it! Does anyone know how to do this? I'm in python 3.8. <https://wiki.vg/Mojang_API#Username_-.3E_UUID_at_time>
2020/07/26
[ "https://Stackoverflow.com/questions/63096451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13996262/" ]
You can find all the documentation [here](https://wiki.vg/Mojang_API) If you read the first few lines you will notice that there is a rate limit of 600 requests per 10 minutes. After that rate limit is reached you will raise a `KeyError`. To fix this we will use a try exception. Don't forget to install the `requests` library. ``` pip3 install requests ``` Getting the user's `uuid` ``` import requests user = "Notch" try: resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{user}") uuid = resp.json()["id"] print(uuid) except KeyError: resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{user}") error = resp.json()["error"] print(error) ``` **Timestamps** If you want to check when a user's username at a certain time period, use a UNIX time. ``` import requests user = "Notch" ts = 1420088400 # Must be a UNIX value. try: resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{user}?at={ts}") uuid = resp.json()["id"] print(uuid) except KeyError: resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{user}?at={ts}") error = resp.json()["error"] print(error) ```
The documentation is relatively straightforward. You want to send a `GET` request with their username: ```py import requests username = "Bob" resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{username}") uuid = resp.json()["id"] print(f"Bob's current UUID is {uuid}") ``` Optionally, you can include a UNIX timestamp to get the username's UUID at a specific point in time: ```py username = "Alice" # UNIX timestamp that equates to 01/01/2018 timestamp = 1514764800 resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{username}?at={timestamp}") uuid = resp.json()["id"] print(f"Alice's UUID on 01/01/2018 was {uuid}") ``` Other Solution (third party library) ------------------------------------ Alternatively, you can use my newly released [Mojang package](https://github.com/summer/mojang), if you don't want to deal with the HTTP requests, JSON, and other web junk in your code. Install it with pip by running the following console command: ``` python -m pip install mojang ``` Usage: ```py from mojang import API api = API() uuid = api.get_uuid("Alice") print(f"Alice's UUID is {uuid}") # or with a timestamp uuid = api.get_uuid("Alice", timestamp=1514764800) print(f"Alice's UUID on 01/01/2018 was {uuid}") ```
65,073,434
I'm using the Mask\_RCNN package from this repo: `https://github.com/matterport/Mask_RCNN`. I tried to train my own dataset using this package but it gives me an error at the beginning. ``` 2020-11-30 12:13:16.577252: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcuda.so.1 2020-11-30 12:13:16.587017: E tensorflow/stream_executor/cuda/cuda_driver.cc:314] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected 2020-11-30 12:13:16.587075: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (7612ade969e5): /proc/driver/nvidia/version does not exist 2020-11-30 12:13:16.587479: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. 2020-11-30 12:13:16.593569: I tensorflow/core/platform/profile_utils/cpu_utils.cc:104] CPU Frequency: 2300000000 Hz 2020-11-30 12:13:16.593811: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x1b2aa00 initialized for platform Host (this does not guarantee that XLA will be used). Devices: 2020-11-30 12:13:16.593846: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version Traceback (most recent call last): File "machines.py", line 345, in <module> model_dir=args.logs) File "/content/Mask_RCNN/mrcnn/model.py", line 1837, in __init__ self.keras_model = self.build(mode=mode, config=config) File "/content/Mask_RCNN/mrcnn/model.py", line 1934, in build anchors = KL.Lambda(lambda x: tf.Variable(anchors), name="anchors")(input_image) File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py", line 926, in __call__ input_list) File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py", line 1117, in _functional_construction_call outputs = call_fn(cast_inputs, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/layers/core.py", line 904, in call self._check_variables(created_variables, tape.watched_variables()) File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/layers/core.py", line 931, in _check_variables raise ValueError(error_str) ValueError: The following Variables were created within a Lambda layer (anchors) but are not tracked by said layer: <tf.Variable 'anchors/Variable:0' shape=(1, 261888, 4) dtype=float32> The layer cannot safely ensure proper Variable reuse across multiple calls, and consquently this behavior is disallowed for safety. Lambda layers are not well suited to stateful computation; instead, writing a subclassed Layer is the recommend way to define layers with Variables. ``` I looked up the part of code responsible for the problem (located at `file: /mrcnn/model.py` `line: 1935` in the repo): `IN[0]: anchors = KL.Lambda(lambda x: tf.Variable(anchors), name="anchors")(input_image)` If anyone have an idea how to solve it or have already solved it, please mention the solution.
2020/11/30
[ "https://Stackoverflow.com/questions/65073434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11919189/" ]
Go to mrcnn/model.py and add: ``` class AnchorsLayer(KL.Layer): def __init__(self, anchors, name="anchors", **kwargs): super(AnchorsLayer, self).__init__(name=name, **kwargs) self.anchors = tf.Variable(anchors) def call(self, dummy): return self.anchors def get_config(self): config = super(AnchorsLayer, self).get_config() return config ``` Then find the line: ``` anchors = KL.Lambda(lambda x: tf.Variable(anchors), name="anchors")(input_image) ``` and replace it with: ``` anchors = AnchorsLayer(anchors, name="anchors")(input_image) ``` Works like a charm in TF 2.4!
ROOT CAUSE: The bahavior of Lambda layer of Keras in Tensorflow 2.X was changed from Tensorflow 1.X. In Keras in Tensorflow 1.X, all tf.Variable and tf.get\_variable are automatically tracked into the layer.weights via variable creator context so they receive gradient and trainable automatically. Such approach has problem with auto graph compilation that convert Python code into Execution Graph in Tensorflow 2.X so it is removed and now Lambda layer has the code to check for variable creation and raise the error as you see. In short, Lambda layer in Tensorflow 2.X has to be stateless. If you want to create variable, the correct way in Tensorflow 2.X is to subclass layer class and add trainable weight as a class member. SOLUTIONS: There are 2 choices - 1. Change to use Tensorflow 1.X.. This error will not be raised. 2. Replace the Lambda layer with subclass of Keras Layer: ``` class AnchorsLayer(tensorflow.keras.layers.Layer): def __init__(self, anchors): super(AnchorLayer, self).__init__() self.anchors_v = tf.Variable(anchors) def call(self): return self.anchors_v # Then replace the Lambda call with this: anchors_layer = AnchorLayers(anchors) anchors = anchors_layer() ```
37,848,815
I develop a web-app using Flask under Python3. I have a problem with postgresql enum type on db migrate/upgrade. I added a column "status" to model: ``` class Banner(db.Model): ... status = db.Column(db.Enum('active', 'inactive', 'archive', name='banner_status')) ... ``` Generated migration by `python manage.py db migrate` is: ``` from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('banner', sa.Column('status', sa.Enum('active', 'inactive', 'archive', name='banner_status'), nullable=True)) def downgrade(): op.drop_column('banner', 'status') ``` And when I do `python manage.py db upgrade` I get an error: ``` ... sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) type "banner_status" does not exist LINE 1: ALTER TABLE banner ADD COLUMN status banner_status [SQL: 'ALTER TABLE banner ADD COLUMN status banner_status'] ``` **Why migration does not create a type "banner\_status"?** **What am I doing wrong?** ``` $ pip freeze alembic==0.8.6 Flask==0.10.1 Flask-Fixtures==0.3.3 Flask-Login==0.3.2 Flask-Migrate==1.8.0 Flask-Script==2.0.5 Flask-SQLAlchemy==2.1 itsdangerous==0.24 Jinja2==2.8 Mako==1.0.4 MarkupSafe==0.23 psycopg2==2.6.1 python-editor==1.0 requests==2.10.0 SQLAlchemy==1.0.13 Werkzeug==0.11.9 ```
2016/06/16
[ "https://Stackoverflow.com/questions/37848815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2111562/" ]
I decided on this problem using that. I changed the code of migration, and migration looks like this: ``` from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status') banner_status.create(op.get_bind()) op.add_column('banner', sa.Column('status', sa.Enum('active', 'inactive', 'archive', name='banner_status'), nullable=True)) def downgrade(): op.drop_column('banner', 'status') banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status') banner_status.drop(op.get_bind()) ``` And now `python manage.py db upgrade\downgrade` is successfully executed.
I think this way is more simple: ``` from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): # others_column = ... banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status', create_type=False), nullable=False) ``` Also added the `postgresql.ENUM` to your `downgrade()` function if that needed.
12,576,734
I have a list which needs to be alphabetized(ignoring lower and uppercase) and printed with spaces and "+" seperating each element in the list. Here's my code: ``` #!/usr/bin/python3.2 fruit = ['A', 'banana', 'Watermelon', 'mango'] #list containing fruits name for diet in sorted(fruit): print(diet) ``` This prints the each fruits in a single line. I want my result to be like this: ``` A + banana + mango + Watermelon ``` How do I achieve this result? Thanks!
2012/09/25
[ "https://Stackoverflow.com/questions/12576734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1687755/" ]
``` In [10]: fruit = ['A', 'banana', 'Watermelon', 'mango'] In [11]: ' + '.join(sorted(fruit, key=str.lower)) Out[11]: 'A + banana + mango + Watermelon' ``` for more detials visit : <http://docs.python.org/library/stdtypes.html#str.join> <http://wiki.python.org/moin/HowTo/Sorting/>
``` print(" + ".join(sorted(fruit, key=str.lower))) ```
39,505,630
This is my first question on stack overflow so bear with me, please. I am trying to download automatically (i.e. scrape) the text of some Italian laws from the website: [http://www.normattiva.it/](http://www.normattiva.it) I am using this code below (and similar permutations): ``` import requests, sys debug = {'verbose': sys.stderr} user_agent = {'User-agent': 'Mozilla/5.0', 'Connection':'keep-alive'} url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&art.idArticolo=1&art.versione=1&art.codiceRedazionale=047U0001&art.dataPubblicazioneGazzetta=1947-12-27&atto.tipoProvvedimento=COSTITUZIONE&art.idGruppo=1&art.idSottoArticolo1=10&art.idSottoArticolo=1&art.flagTipoArticolo=0#art' r = requests.session() s = r.get(url, headers=user_agent) #print(s.text) print(s.url) print(s.headers) print(s.request.headers) ``` As you can see I am trying to load the "**caricaArticolo**" query. However, the output is a page saying that my search is invalid (***"session is not valid or expired"***) It seems that the page recognizes that I am not using a browser and loads a "breakout" javascript function. ``` <body onload="javascript:breakout();"> ``` I tried to use "browser" simulator python scripts such as **selenium** and **robobrowser** but the result is the same. Is there anyone who is willing to spend 10 minutes looking at the page output and give help?
2016/09/15
[ "https://Stackoverflow.com/questions/39505630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6696413/" ]
Once you click any link on the page with dev tools open, under the doc tab under Network: [![enter image description here](https://i.stack.imgur.com/orZHr.png)](https://i.stack.imgur.com/orZHr.png) You can see three links, the first is what we click on, the second returns the html that allows you to jump to a specific *Article* and the last contains the article text. In the source returned from the firstlink, you can see two *iframe* tags: ``` <div id="alberoTesto"> <iframe src="/atto/caricaAlberoArticoli?atto.dataPubblicazioneGazzetta=2016-08-31&atto.codiceRedazionale=16G00182&atto.tipoProvvedimento=DECRETO LEGISLATIVO" name="leftFrame" scrolling="auto" id="leftFrame" title="leftFrame" height="100%" style="width: 285px; float:left;" frameborder="0"> </iframe> <iframe src="/atto/caricaArticoloDefault?atto.dataPubblicazioneGazzetta=2016-08-31&atto.codiceRedazionale=16G00182&atto.tipoProvvedimento=DECRETO LEGISLATIVO" name="mainFrame" id="mainFrame" title="mainFrame" height="100%" style="width: 800px; float:left;" scrolling="auto" frameborder="0"> </iframe> ``` The first is for the Article, the latter with */caricaArticoloDefault* and the *id* *mainFrame* is what we want. You need to use the cookies from the initial requests so you can do it with the *Session* object and by parsing the pages using [bs4](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all-next-and-find-next): ``` import requests, sys import os from urlparse import urljoin import io user_agent = {'User-agent': 'Mozilla/5.0', 'Connection': 'keep-alive'} url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&art.idArticolo=1&art.versione=1&art.codiceRedazionale=047U0001&art.dataPubblicazioneGazzetta=1947-12-27&atto.tipoProvvedimento=COSTITUZIONE&art.idGruppo=1&art.idSottoArticolo1=10&art.idSottoArticolo=1&art.flagTipoArticolo=0#art' with requests.session() as s: s.headers.update(user_agent) r = s.get("http://www.normattiva.it/") soup = BeautifulSoup(r.content, "lxml") # get all the links from the initial page for a in soup.select("div.testo p a[href^=http]"): soup = BeautifulSoup(s.get(a["href"]).content) # The link to the text is in a iframe tag retuened from the previous get. text_src_link = soup.select_one("#mainFrame")["src"] # Pick something to make the names unique with io.open(os.path.basename(text_src_link), "w", encoding="utf-8") as f: # The text is in pre tag that is in the div with the pre class text = BeautifulSoup(s.get(urljoin("http://www.normattiva.it", text_src_link)).content, "html.parser")\ .select_one("div.wrapper_pre pre").text f.write(text) ``` A snippet of the first text file: ``` IL PRESIDENTE DELLA REPUBBLICA Visti gli articoli 76, 87 e 117, secondo comma, lettera d), della Costituzione; Vistala legge 28 novembre 2005, n. 246 e, in particolare, l'articolo 14: comma 14, cosi' come sostituito dall'articolo 4, comma 1, lettera a), della legge 18 giugno 2009, n. 69, con il quale e' stata conferita al Governo la delega ad adottare, con le modalita' di cui all'articolo 20 della legge 15 marzo 1997, n. 59, decreti legislativi che individuano le disposizioni legislative statali, pubblicate anteriormente al 1° gennaio 1970, anche se modificate con provvedimenti successivi, delle quali si ritiene indispensabile la permanenza in vigore, secondo i principi e criteri direttivi fissati nello stesso comma 14, dalla lettera a) alla lettera h); comma 15, con cui si stabilisce che i decreti legislativi di cui al citato comma 14, provvedono, altresi', alla semplificazione o al riassetto della materia che ne e' oggetto, nel rispetto dei principi e criteri direttivi di cui all'articolo 20 della legge 15 marzo 1997, n. 59, anche al fine di armonizzare le disposizioni mantenute in vigore con quelle pubblicate successivamente alla data del 1° gennaio 1970; comma 22, con cui si stabiliscono i termini per l'acquisizione del prescritto parere da parte della Commissione parlamentare per la semplificazione; Visto il decreto legislativo 30 luglio 1999, n. 300, recante riforma dell'organizzazione del Governo, a norma dell'articolo 11 della legge 15 marzo 1997, n. 59 e, in particolare, gli articoli da 20 a 22; ```
wonderful, wonderful, wonderful Padraic. It works. Just had to edits slightly to clear imports but it's works wonderfully. Thanks very much. I am just discovering python's potential and you have made my journey much easier with this specific task. I would have not solved it alone. ``` import requests, sys import os from urllib.parse import urljoin from bs4 import BeautifulSoup import io user_agent = {'User-agent': 'Mozilla/5.0', 'Connection': 'keep-alive'} url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&art.idArticolo=1&art.versione=1&art.codiceRedazionale=047U0001&art.dataPubblicazioneGazzetta=1947-12-27&atto.tipoProvvedimento=COSTITUZIONE&art.idGruppo=1&art.idSottoArticolo1=10&art.idSottoArticolo=1&art.flagTipoArticolo=0#art' with requests.session() as s: s.headers.update(user_agent) r = s.get("http://www.normattiva.it/") soup = BeautifulSoup(r.content, "lxml") # get all the links from the initial page for a in soup.select("div.testo p a[href^=http]"): soup = BeautifulSoup(s.get(a["href"]).content) # The link to the text is in a iframe tag retuened from the previous get. text_src_link = soup.select_one("#mainFrame")["src"] # Pick something to make the names unique with io.open(os.path.basename(text_src_link), "w", encoding="utf-8") as f: # The text is in pre tag that is in the div with the pre class text = BeautifulSoup(s.get(urljoin("http://www.normattiva.it", text_src_link)).content, "html.parser")\ .select_one("div.wrapper_pre pre").text f.write(text) ```
61,209,143
Python : 3.7.6 rpy2: 3.2.7 R: 3.3.3 I’m using GCE at AI Platform to perform some clustering. I’ve installed the r-base, updated properly, installed the python-rpy2 and I’m getting this error. ```py import rpy2.robjects as robjects error: symbol 'R_tryCatchError' not found in library '/usr/lib/R/lib/libR.so': /usr/lib/R/lib/libR.so: undefined symbol: R_tryCatchError ``` Someone could help me?
2020/04/14
[ "https://Stackoverflow.com/questions/61209143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13214910/" ]
Here's a one-liner to update it without mutating the original array: ```js const updatedPersons = persons.map(p => p.id === id ? {...p, lastname} : p); ```
``` persons.forEach(person => { if(this.id === person.id) person.lastname = this.lastname }) ```
61,209,143
Python : 3.7.6 rpy2: 3.2.7 R: 3.3.3 I’m using GCE at AI Platform to perform some clustering. I’ve installed the r-base, updated properly, installed the python-rpy2 and I’m getting this error. ```py import rpy2.robjects as robjects error: symbol 'R_tryCatchError' not found in library '/usr/lib/R/lib/libR.so': /usr/lib/R/lib/libR.so: undefined symbol: R_tryCatchError ``` Someone could help me?
2020/04/14
[ "https://Stackoverflow.com/questions/61209143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13214910/" ]
Here's a one-liner to update it without mutating the original array: ```js const updatedPersons = persons.map(p => p.id === id ? {...p, lastname} : p); ```
You need to loop over the array and add a condition to check if id matches `person.id` then add `lastname` to that person object. If you don't want to change the original array go for `.map()` else `.forEach()` With `.forEach()`: ``` persons.forEach(person => { if (person.id === id) { person.lastname = lastname } }) ``` With `.map()`: ``` const newPersonsArr = persons.map(person => { if (person.id === id) { return { ...person, lastname } } return person; }) ```
14,693,256
I've just finished up installing mod\_wsgi but I'm having problems starting my Pyramid application. I'm using python 2.7, Apache 2.2.3, mod\_wsgi 3.4 on CentOS 5.8 Here is my httpd.config file ``` WSGISocketPrefix run/wsgi <VirtualHost *:80> ServerName myapp.domain.com ServerAlias myapp WSGIApplicationGroup %{GLOBAL} WSGIPassAuthorization On WSGIDaemonProcess pyramid user=apache group=apache processes=1 threads=4 \ python-path=/var/wsgi_sites/site-packages WSGIScriptAlias / /var/wsgi_sites/myapp/apache.wsgi <Directory /var/wsgi_sites/myapp> WSGIProcessGroup pyramid Order allow,deny Allow from all </Directory> LogLevel debug ErrorLog /var/log/httpd/myapp_error </VirtualHost> ``` I have given Apache ownership of site-package, python-eggs and myapp folders. Module which I'm using to create WSGI application appache.wsgi contains the following code ``` import os os.environ['PYTHON_EGG_CACHE'] = '/var/wsgi_sites/python-eggs' from pyramid.paster import get_app application = get_app('/var/wsgi_sites/myapp/development.ini','main') ``` When I restart Apache and try to access application I get the following error ``` mod_wsgi (pid=14842, process='pyramid', application=''): Loading WSGI script '/var/wsgi_sites/myapp/apache.wsgi'. mod_wsgi (pid=14842): Target WSGI script '/var/wsgi_sites/myapp/apache.wsgi' cannot be loaded as Python module. mod_wsgi (pid=14842): Exception occurred processing WSGI script '/var/wsgi_sites/myapp/apache.wsgi'. Traceback (most recent call last): File "/var/wsgi_sites/myapp/apache.wsgi", line 4, in ? from pyramid.paster import get_app File "/var/wsgi_sites/site-packages/pyramid-1.3.2-py2.7.egg/pyramid/__init__.py", line 1, in ? from pyramid.request import Request File "/var/wsgi_sites/site-packages/pyramid-1.3.2-py2.7.egg/pyramid/request.py", line class Request(BaseRequest, DeprecatedRequestMethodsMixin, URLMethodsMixin, ^ SyntaxError: invalid syntax ``` I tried looking at the request.py file but there are no syntax errors.
2013/02/04
[ "https://Stackoverflow.com/questions/14693256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1210711/" ]
Often when you get syntax errors the preceding line is the culprit. Looking at [the Pyramid source](https://github.com/Pylons/pyramid/blob/master/pyramid/request.py) we see that the preceding line is: ``` @implementer(IRequest) ``` This is a class-decorator. Class-decorators were added to Python in version 2.6. The default version of Python on CentOS 5.8 is 2.4. Your solution is to either: 1. use an OS with a more recent version of Python, or 2. ensure that your Pyramid application uses version 2.7. This involves installing Python 2.7 **in addition to** the system's default Python installation which is used by other applications and must be left alone. If you choose to install 2.7 you will do something like the following: ``` $ wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tar.bz2 $ tar xf Python-2.7.3.tar.bz2 $ cd Python-2.7.3 $ ./configure --prefix=/usr/local $ make && make altinstall ```
I see two different wsgi files mentioned in the error /var/wsgi\_sites/project\_name\_api/apache.wsgi and /var/wsgi\_sites/myapp/apache.wsgi I cannot see any project\_name path reference in the httpd.conf that you pasted. You might want to start by reviewing that. If the problem persists then please post additional information to help you further.
47,747,532
I'm confronted with a problem as below and hoping some body could give some advice. I need to convert a lot of excel tables in different shapes into constructed data, the excel tables are as below. ``` |--------------------|----|----| |user:Sam | | | |--------------------|----|----| |mail:sam@example.com| | | |-------|----------------|-----| |user |Jack | | |-------|----------------|-----| |mail |jack@example.com| | |-------|----------------|-----| |-------|-----|---------------|---------| |user |May | | | |-------|-----|---------------|---------| | |mail |may@example.com| | |-------|-----|---------------|---------| |user | Alex |mail |alex@example.com| ``` The target result would be like the following format. ``` |-------|-------------------| |user | email | |-------|-------------------| |Jack | jack@example.com | |-------|-------------------| |Sam | sam@example.com | |-------|-------------------| |Alex | alex@example.com | |-------|-------------------| |May | may@example.com | |-------|-------------------| ``` My current solution is to define a function for each type of excel table. But there would be thousands of different excel files so I would have to repeat write similar code. So my question is whether there is common solution for it. I found one [similar question](https://stackoverflow.com/questions/32089023/looking-for-a-little-python-machine-learning-advice) about this but there is no more information.I think machine learning may help to solve the problem, but I know little about that. Is there any one who could share some thoughts? Thanks very much!
2017/12/11
[ "https://Stackoverflow.com/questions/47747532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8226471/" ]
Looking at the patterns you have provided in your question we see that the data is sometimes in a separate cell, other times encoded in the text with a ':' separator. I'd flatten it out and parse the assembled text for a linear pattern. I suggest you read the excel file using something like [xlrd](https://pypi.python.org/pypi/xlrd). Then step through the cells pulling out the text and parse out the fields you are interested in. ``` <cell>'user'<cell|':'>user_name<cell>'mail'<cell|':'>email_address<cell> ``` where `<cell>` is one or more cell boundaries, possibly spread over rows. Once you have the user email pairs you can write them out using [xlwt](https://pypi.python.org/pypi/xlwt).
You have 4 types of files. If that is all you can write 1 function with 4 if statements. ``` def table_sort(file): If file == condition: extract_data_this_way elif file == other_condition: extract_data_this_way elif file == other_condition: extract_data_this_way else: extract_data_this_way ``` If you use pandas to do this it will make it a lot easier to code. I'd you have a lot of files. You can pass in a list and use a for loop to iterate. Or use glob to load all excel files in a directory and loop that way .
18,314,228
I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g: ``` List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] ``` How can i achieve this in python ? Thank you
2013/08/19
[ "https://Stackoverflow.com/questions/18314228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413734/" ]
I think you should use dictionaries ``` >>> dict_sublist = {} >>> for el in List: ... dict_sublist.setdefault(len(el), []).append(el) ... >>> dict_sublist {1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['dddd']} ```
Assuming you're happy with a list of lists, indexed by length, how about something like ``` by_length = [] for word in List: wl = len(word) while len(by_length) < wl: by_length.append([]) by_length[wl].append(word) print "The words of length 3 are %s" % by_length[3] ```
18,314,228
I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g: ``` List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] ``` How can i achieve this in python ? Thank you
2013/08/19
[ "https://Stackoverflow.com/questions/18314228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413734/" ]
by using `itertools.groupby`: ``` values = ['a', 'bb', 'aa', 'ccc', 'dddd', 'eee'] from itertools import groupby output = [list(group) for key,group in groupby(sorted(values, key=len), key=len)] ``` The result is: ``` [['a'], ['bb', 'aa'], ['ccc', 'eee'], ['dddd']] ``` If your list is already sorted by string length and you just need to do grouping, then you can simplify the code to: ``` output = [list(group) for key,group in groupby(values, key=len)] ```
I think you should use dictionaries ``` >>> dict_sublist = {} >>> for el in List: ... dict_sublist.setdefault(len(el), []).append(el) ... >>> dict_sublist {1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['dddd']} ```
18,314,228
I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g: ``` List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] ``` How can i achieve this in python ? Thank you
2013/08/19
[ "https://Stackoverflow.com/questions/18314228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413734/" ]
I think you should use dictionaries ``` >>> dict_sublist = {} >>> for el in List: ... dict_sublist.setdefault(len(el), []).append(el) ... >>> dict_sublist {1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['dddd']} ```
``` >>> from collections import defaultdict >>> l = ["a", "bb", "aa", "ccc", "dddd"] >>> d = defaultdict(list) >>> for elem in l: ... d[len(elem)].append(elem) ... >>> sublists = list(d.values()) >>> print(sublists) [['a'], ['bb', 'aa'], ['ccc'], ['dddd']] ```