code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# together with waitkeys later, helps to close the video window effectively _cv2.startWindowThread() for frame in stream.frame_generator(): if frame is not None: _cv2.imshow('Video', frame) _cv2.moveWindow('Video',5,5) else: break key = _cv2.waitKey(1) & 0xFF if key == ord("q"): break _cv2.waitKey(1) _cv2.destroyAllWindows() _cv2.waitKey(1)
def preview_stream(stream)
Display stream in an OpenCV window until "q" key is pressed
3.915099
3.664649
1.068342
try: recst = recst.decode('UTF-8') except AttributeError: pass recs=[ x for x in recst.split('\r\n') if x ] for rec in recs: print(rec) print("\n")
def printrec(recst)
Pretty-printing rtsp strings
3.052402
2.908397
1.049513
resp = connection.describe(verbose=False).split('\r\n') resources = [x.replace('a=control:','') for x in resp if (x.find('control:') != -1 and x[-1] != '*' )] return resources
def get_resources(connection)
Do an RTSP-DESCRIBE request, then parse out available resources from the response
8.337197
6.208644
1.342837
self.rtsp_seq += 1 uri = '/'.join([s.strip('/') for s in (self.server,self.stream_path,resource_path)]) ## example: SETUP rtsp://example.com/foo/bar/baz.rm RTSP/2.0 request = f"SETUP rtsp://{uri} {RTSP_VER}\r\n" request+= f"CSeq: {self.rtsp_seq}\r\n" request+= f"Transport: RTP/AVP;unicast;client_port=5000-5001\r\n"#,RTP/SAVPF,RTP/AVP;unicast;client_port=5000-5001,RTP/AVP/UDP;unicast;client_port=5000-5001\r\n" #request+= f"Accept-Ranges: npt, smpte, clock\r\n" request+= f"User-Agent: python\r\n\r\n" reply = self.sendMessage(request.encode('UTF-8')) return reply
def setup(self,resource_path = "track1")
SETUP method defined by RTSP Protocol - https://tools.ietf.org/html/rfc7826#section-13.3
3.543703
3.29459
1.075613
self._check_ffmpeg() cmd = "ffmpeg -rtsp_transport tcp -i {} -loglevel quiet -frames 1 -f image2pipe -".format(rtsp_server_uri) #stdout = _sp.check_output(ffmpeg_cmd,timeout = timeout_secs) with _sp.Popen(cmd, shell=True, stdout=_sp.PIPE) as process: try: stdout,stderr = process.communicate(timeout=timeout_secs) except _sp.TimeoutExpired as e: process.kill() raise TimeoutError("Connection to {} timed out".format(rtsp_server_uri),e) return _Image.open(_io.BytesIO(stdout))
def fetch_image(self,rtsp_server_uri = _source,timeout_secs = 15)
Fetch a single frame using FFMPEG. Convert to PIL Image. Slow.
2.851722
2.741007
1.040392
'''根据命令执行操作''' global CUR_RANGE,CUR_SCALE if cmd in ('exit','teardown'): rtsp.do_teardown() elif cmd == 'pause': CUR_SCALE = 1; CUR_RANGE = 'npt=now-' rtsp.do_pause() elif cmd == 'help': PRINT(play_ctrl_help()) elif cmd == 'forward': if CUR_SCALE < 0: CUR_SCALE = 1 CUR_SCALE *= 2; CUR_RANGE = 'npt=now-' elif cmd == 'backward': if CUR_SCALE > 0: CUR_SCALE = -1 CUR_SCALE *= 2; CUR_RANGE = 'npt=now-' elif cmd == 'begin': CUR_SCALE = 1; CUR_RANGE = 'npt=beginning-' elif cmd == 'live': CUR_SCALE = 1; CUR_RANGE = 'npt=end-' elif cmd.startswith('play'): m = re.search(r'range[:\s]+(?P<range>[^\s]+)',cmd) if m: CUR_RANGE = m.group('range') m = re.search(r'scale[:\s]+(?P<scale>[\d\.]+)',cmd) if m: CUR_SCALE = int(m.group('scale')) if cmd not in ('pause','exit','teardown','help'): rtsp.do_play(CUR_RANGE,CUR_SCALE)
def exec_cmd(rtsp,cmd)
根据命令执行操作
2.863341
2.823296
1.014184
'''解析url,返回(ip,port,target)三元组''' (ip,port,target) = ('',DEFAULT_SERVER_PORT,'') m = re.match(r'[rtspRTSP:/]+(?P<ip>(\d{1,3}\.){3}\d{1,3})(:(?P<port>\d+))?(?P<target>.*)',url) if m is not None: ip = m.group('ip') port = int(m.group('port')) target = m.group('target') #PRINT('ip: %s, port: %d, target: %s'%(ip,port,target), GREEN) return ip,port,target
def _parse_url(self,url)
解析url,返回(ip,port,target)三元组
3.430026
2.987263
1.148217
'''连接服务器,建立socket''' try: self._sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self._sock.connect((self._server_ip,self._server_port)) #PRINT('Connect [%s:%d] success!'%(self._server_ip,self._server_port), GREEN) except socket.error, e: sys.stderr.write('ERROR: %s[%s:%d]'%(e,self._server_ip,self._server_port)) traceback.print_exc() sys.exit(1)
def _connect_server(self)
连接服务器,建立socket
2.850253
2.69454
1.057788
'''如果未指定DEST_IP,默认与RTSP使用相同IP''' global DEST_IP if not DEST_IP: DEST_IP = self._sock.getsockname()[0] PRINT('DEST_IP: %s\n'%DEST_IP, CYAN)
def _update_dest_ip(self)
如果未指定DEST_IP,默认与RTSP使用相同IP
8.877783
4.027512
2.204285
'''收取一个完整响应消息或ANNOUNCE通知消息''' try: while True: if HEADER_END_STR in self._recv_buf: break more = self._sock.recv(2048) if not more: break self._recv_buf += more except socket.error, e: PRINT('Receive data error: %s'%e,RED) sys.exit(-1) msg = '' if self._recv_buf: (msg,self._recv_buf) = self._recv_buf.split(HEADER_END_STR,1) content_length = self._get_content_length(msg) msg += HEADER_END_STR + self._recv_buf[:content_length] self._recv_buf = self._recv_buf[content_length:] return msg
def recv_msg(self)
收取一个完整响应消息或ANNOUNCE通知消息
3.70702
2.879825
1.287238
'''从消息中解析Content-length''' m = re.search(r'[Cc]ontent-length:\s?(?P<len>\d+)',msg,re.S) return (m and int(m.group('len'))) or 0
def _get_content_length(self,msg)
从消息中解析Content-length
4.361485
3.5575
1.225997
'''处理响应消息''' status,headers,body = self._parse_response(msg) rsp_cseq = int(headers['cseq']) if self._cseq_map[rsp_cseq] != 'GET_PARAMETER': PRINT(self._get_time_str() + '\n' + msg) if status == 302: self.location = headers['location'] if status != 200: self.do_teardown() if self._cseq_map[rsp_cseq] == 'DESCRIBE': track_id_str = self._parse_track_id(body) self.do_setup(track_id_str) elif self._cseq_map[rsp_cseq] == 'SETUP': self._session_id = headers['session'] self.do_play(CUR_RANGE,CUR_SCALE) self.send_heart_beat_msg() elif self._cseq_map[rsp_cseq] == 'PLAY': self.playing = True
def _process_response(self,msg)
处理响应消息
4.194813
4.1423
1.012677
'''处理ANNOUNCE通知消息''' global CUR_RANGE,CUR_SCALE PRINT(msg) headers = self._parse_header_params(msg.splitlines()[1:]) x_notice_val = int(headers['x-notice']) if x_notice_val in (X_NOTICE_EOS,X_NOTICE_BOS): CUR_SCALE = 1 self.do_play(CUR_RANGE,CUR_SCALE) elif x_notice_val == X_NOTICE_CLOSE: self.do_teardown()
def _process_announce(self,msg)
处理ANNOUNCE通知消息
7.100718
6.50393
1.091758
'''解析响应消息''' header,body = msg.split(HEADER_END_STR)[:2] header_lines = header.splitlines() version,status = header_lines[0].split(None,2)[:2] headers = self._parse_header_params(header_lines[1:]) return int(status),headers,body
def _parse_response(self,msg)
解析响应消息
4.039508
3.708806
1.089167
'''解析头部参数''' headers = {} for line in header_param_lines: if line.strip(): # 跳过空行 key,val = line.split(':', 1) headers[key.lower()] = val.strip() return headers
def _parse_header_params(self,header_param_lines)
解析头部参数
2.849157
2.546879
1.118686
'''从sdp中解析trackID=2形式的字符串''' m = re.search(r'a=control:(?P<trackid>[\w=\d]+)',sdp,re.S) return (m and m.group('trackid')) or ''
def _parse_track_id(self,sdp)
从sdp中解析trackID=2形式的字符串
6.502192
3.626939
1.792749
'''发送消息''' msg = '%s %s %s'%(method,url,RTSP_VERSION) headers['User-Agent'] = DEFAULT_USERAGENT cseq = self._next_seq() self._cseq_map[cseq] = method headers['CSeq'] = str(cseq) if self._session_id: headers['Session'] = self._session_id for (k,v) in headers.items(): msg += LINE_SPLIT_STR + '%s: %s'%(k,str(v)) msg += HEADER_END_STR # End headers if method != 'GET_PARAMETER' or 'x-RetransSeq' in headers: PRINT(self._get_time_str() + LINE_SPLIT_STR + msg) try: self._sock.send(msg) except socket.error, e: PRINT('Send msg error: %s'%e, RED)
def _sendmsg(self,method,url,headers)
发送消息
4.677595
4.716898
0.991668
'''获取SETUP时需要的Transport字符串参数''' transport_str = '' ip_type = 'unicast' #if IPAddress(DEST_IP).is_unicast() else 'multicast' for t in TRANSPORT_TYPE_LIST: if t not in TRANSPORT_TYPE_MAP: PRINT('Error param: %s'%t,RED) sys.exit(1) if t.endswith('tcp'): transport_str += TRANSPORT_TYPE_MAP[t]%ip_type else: transport_str += TRANSPORT_TYPE_MAP[t]%(ip_type,DEST_IP,CLIENT_PORT_RANGE) return transport_str
def _get_transport_type(self)
获取SETUP时需要的Transport字符串参数
6.021136
4.341588
1.386851
'''定时发送GET_PARAMETER消息保活''' if self.running: self.do_get_parameter() threading.Timer(HEARTBEAT_INTERVAL, self.send_heart_beat_msg).start()
def send_heart_beat_msg(self)
定时发送GET_PARAMETER消息保活
7.363174
3.670775
2.005891
if self.state == self.INIT: self.sendRtspRequest(self.SETUP)
def setupMovie(self)
Setup button handler.
16.312798
17.267254
0.944724
self.sendRtspRequest(self.TEARDOWN) #self.handler() os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video rate = float(self.counter/self.frameNbr) print('-'*60 + "\nRTP Packet Loss Rate :" + str(rate) +"\n" + '-'*60) sys.exit(0)
def exitClient(self)
Teardown button handler.
10.886162
10.216319
1.065566
if self.state == self.PLAYING: self.sendRtspRequest(self.PAUSE)
def pauseMovie(self)
Pause button handler.
11.251997
10.454156
1.076318
try: photo = ImageTk.PhotoImage(Image.open(imageFile)) #stuck here !!!!!! except: print("photo error") print('-'*60) traceback.print_exc(file=sys.stdout) print('-'*60) self.label.configure(image = photo, height=288) self.label.image = photo
def updateMovie(self, imageFile)
Update the image file as video frame in the GUI.
4.525313
4.368531
1.035889
self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.rtspSocket.connect((self.serverAddr, self.serverPort)) except: tkinter.messagebox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' %self.serverAddr)
def connectToServer(self)
Connect to the Server. Start a new RTSP/TCP session.
2.861819
2.503272
1.143231
#------------- # TO COMPLETE #------------- # Setup request if requestCode == self.SETUP and self.state == self.INIT: threading.Thread(target=self.recvRtspReply).start() # Update RTSP sequence number. # ... self.rtspSeq = 1 # Write the RTSP request to be sent. # request = ... request = "SETUP " + str(self.fileName) + "\n" + str(self.rtspSeq) + "\n" + " RTSP/1.0 RTP/UDP " + str(self.rtpPort) self.rtspSocket.send(request) # Keep track of the sent request. # self.requestSent = ... self.requestSent = self.SETUP # Play request elif requestCode == self.PLAY and self.state == self.READY: # Update RTSP sequence number. # ... self.rtspSeq = self.rtspSeq + 1 # Write the RTSP request to be sent. # request = ... request = "PLAY " + "\n" + str(self.rtspSeq) self.rtspSocket.send(request) print('-'*60 + "\nPLAY request sent to Server...\n" + '-'*60) # Keep track of the sent request. # self.requestSent = ... self.requestSent = self.PLAY # Pause request elif requestCode == self.PAUSE and self.state == self.PLAYING: # Update RTSP sequence number. # ... self.rtspSeq = self.rtspSeq + 1 # Write the RTSP request to be sent. # request = ... request = "PAUSE " + "\n" + str(self.rtspSeq) self.rtspSocket.send(request) print('-'*60 + "\nPAUSE request sent to Server...\n" + '-'*60) # Keep track of the sent request. # self.requestSent = ... self.requestSent = self.PAUSE # Resume request # Teardown request elif requestCode == self.TEARDOWN and not self.state == self.INIT: # Update RTSP sequence number. # ... self.rtspSeq = self.rtspSeq + 1 # Write the RTSP request to be sent. # request = ... request = "TEARDOWN " + "\n" + str(self.rtspSeq) self.rtspSocket.send(request) print('-'*60 + "\nTEARDOWN request sent to Server...\n" + '-'*60) # Keep track of the sent request. # self.requestSent = ... self.requestSent = self.TEARDOWN else: return
def sendRtspRequest(self, requestCode)
Send RTSP request to the server.
2.066765
2.045581
1.010356
while True: reply = self.rtspSocket.recv(1024) if reply: self.parseRtspReply(reply) # Close the RTSP socket upon requesting Teardown if self.requestSent == self.TEARDOWN: self.rtspSocket.shutdown(socket.SHUT_RDWR) self.rtspSocket.close() break
def recvRtspReply(self)
Receive RTSP reply from the server.
3.722929
3.622947
1.027597
print("Parsing Received Rtsp data...") lines = data.split('\n') seqNum = int(lines[1].split(' ')[1]) # Process only if the server reply's sequence number is the same as the request's if seqNum == self.rtspSeq: session = int(lines[2].split(' ')[1]) # New RTSP session ID if self.sessionId == 0: self.sessionId = session # Process only if the session ID is the same if self.sessionId == session: if int(lines[0].split(' ')[1]) == 200: if self.requestSent == self.SETUP: #------------- # TO COMPLETE #------------- # Update RTSP state. print("Updating RTSP state...") # self.state = ... self.state = self.READY # Open RTP port. #self.openRtpPort() print("Setting Up RtpPort for Video Stream") self.openRtpPort() elif self.requestSent == self.PLAY: self.state = self.PLAYING print('-'*60 + "\nClient is PLAYING...\n" + '-'*60) elif self.requestSent == self.PAUSE: self.state = self.READY # The play thread exits. A new thread is created on resume. self.playEvent.set() elif self.requestSent == self.TEARDOWN: # self.state = ... # Flag the teardownAcked to close the socket. self.teardownAcked = 1
def parseRtspReply(self, data)
Parse the RTSP reply from the server.
5.246989
5.115132
1.025778
#------------- # TO COMPLETE #------------- # Create a new datagram socket to receive RTP packets from the server # self.rtpSocket = ... # Set the timeout value of the socket to 0.5sec # ... self.rtpSocket.settimeout(0.5) # try: # Bind the socket to the address using the RTP port given by the client user # ... # except: # tkMessageBox.showwarning('Unable to Bind', 'Unable to bind PORT=%d' %self.rtpPort) try: #self.rtpSocket.connect(self.serverAddr,self.rtpPort) self.rtpSocket.bind((self.serverAddr,self.rtpPort)) # WATCH OUT THE ADDRESS FORMAT!!!!! rtpPort# should be bigger than 1024 #self.rtpSocket.listen(5) print("Bind RtpPort Success") except: tkinter.messagebox.showwarning('Connection Failed', 'Connection to rtpServer failed...')
def openRtpPort(self)
Open RTP socket binded to a specified port.
6.098792
6.128047
0.995226
stream = BytesIO() self.cam.capture(stream, format='png') # "Rewind" the stream to the beginning so we can read its content stream.seek(0) return Image.open(stream)
def read(self)
https://picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-to-a-pil-image
4.538608
3.161322
1.435667
win_name = 'Camera' cv2.namedWindow(win_name, cv2.WINDOW_AUTOSIZE) cv2.moveWindow(win_name,20,20) self.open() while(self.isOpened()): cv2.imshow(win_name,self._stream.read()[1]) if cv2.waitKey(25) & 0xFF == ord('q'): break cv2.waitKey() cv2.destroyAllWindows() cv2.waitKey()
def preview(self)
Blocking function. Opens OpenCV window to display stream.
2.479739
2.144326
1.156419
# Create Setup button self.setup = Button(self.master, width=20, padx=3, pady=3) self.setup["text"] = "Setup" self.setup["command"] = self.setupMovie self.setup.grid(row=1, column=0, padx=2, pady=2) # Create Play button self.start = Button(self.master, width=20, padx=3, pady=3) self.start["text"] = "Play" self.start["command"] = self.playMovie self.start.grid(row=1, column=1, padx=2, pady=2) # Create Pause button self.pause = Button(self.master, width=20, padx=3, pady=3) self.pause["text"] = "Pause" self.pause["command"] = self.pauseMovie self.pause.grid(row=1, column=2, padx=2, pady=2) # Create Teardown button self.teardown = Button(self.master, width=20, padx=3, pady=3) self.teardown["text"] = "Teardown" self.teardown["command"] = self.exitClient self.teardown.grid(row=1, column=3, padx=2, pady=2) # Create a label to display the movie self.label = Label(self.master, height=19) self.label.grid(row=0, column=0, columnspan=4, sticky=W+E+N+S, padx=5, pady=5)
def createWidgets(self)
Build GUI.
1.619957
1.599979
1.012486
if self.state == self.READY: # Create a new thread to listen for RTP packets print "Playing Movie" threading.Thread(target=self.listenRtp).start() self.playEvent = threading.Event() self.playEvent.clear() self.sendRtspRequest(self.PLAY)
def playMovie(self)
Play button handler.
5.354016
5.373193
0.996431
cachename = CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT try: file = open(cachename, "wb") except: print "file open error" try: file.write(data) except: print "file write error" file.close() return cachename
def writeFrame(self, data)
Write the received frame to a temp image file. Return the image file.
3.667716
3.362419
1.090797
self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.rtspSocket.connect((self.serverAddr, self.serverPort)) except: tkMessageBox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' %self.serverAddr)
def connectToServer(self)
Connect to the Server. Start a new RTSP/TCP session.
2.818536
2.433594
1.158178
#------------- # TO COMPLETE #------------- # Create a new datagram socket to receive RTP packets from the server # self.rtpSocket = ... # Set the timeout value of the socket to 0.5sec # ... self.rtpSocket.settimeout(0.5) # try: # Bind the socket to the address using the RTP port given by the client user # ... # except: # tkMessageBox.showwarning('Unable to Bind', 'Unable to bind PORT=%d' %self.rtpPort) try: #self.rtpSocket.connect(self.serverAddr,self.rtpPort) self.rtpSocket.bind((self.serverAddr,self.rtpPort)) # WATCH OUT THE ADDRESS FORMAT!!!!! rtpPort# should be bigger than 1024 #self.rtpSocket.listen(5) print "Bind RtpPort Success" except: tkMessageBox.showwarning('Connection Failed', 'Connection to rtpServer failed...')
def openRtpPort(self)
Open RTP socket binded to a specified port.
5.956524
5.987744
0.994786
self.pauseMovie() if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"): self.exitClient() else: # When the user presses cancel, resume playing. #self.playMovie() print "Playing Movie" threading.Thread(target=self.listenRtp).start() #self.playEvent = threading.Event() #self.playEvent.clear() self.sendRtspRequest(self.PLAY)
def handler(self)
Handler on explicitly closing the GUI window.
6.49712
6.377662
1.018731
timestamp = int(time()) print("timestamp: " + str(timestamp)) self.header = bytearray(HEADER_SIZE) #-------------- # TO COMPLETE #-------------- # Fill the header bytearray with RTP header fields #RTP-version filed(V), must set to 2 #padding(P),extension(X),number of contributing sources(CC) and marker(M) fields all set to zero in this lab #Because we have no other contributing sources(field CC == 0),the CSRC-field does not exist #Thus the length of the packet header is therefore 12 bytes #Above all done in ServerWorker.py # ... #header[] = #header[0] = version + padding + extension + cc + seqnum + marker + pt + ssrc self.header[0] = version << 6 self.header[0] = self.header[0] | padding << 5 self.header[0] = self.header[0] | extension << 4 self.header[0] = self.header[0] | cc self.header[1] = marker << 7 self.header[1] = self.header[1] | pt self.header[2] = seqnum >> 8 self.header[3] = seqnum self.header[4] = (timestamp >> 24) & 0xFF self.header[5] = (timestamp >> 16) & 0xFF self.header[6] = (timestamp >> 8) & 0xFF self.header[7] = timestamp & 0xFF self.header[8] = ssrc >> 24 self.header[9] = ssrc >> 16 self.header[10] = ssrc >> 8 self.header[11] = ssrc # Get the payload from the argument # self.payload = ... self.payload = payload
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload)
Encode the RTP packet with header fields and payload.
3.477155
3.436831
1.011733
for pos, element in self.element_iter: tag, class_attr = _tag_and_class_attr(element) if tag == "div" and "thread" in class_attr and pos == "end": break
def skip(self)
Eats through the input iterator without recording the content.
8.394455
8.023551
1.046227
tag, class_attr = _tag_and_class_attr(e) start_of_message = tag == 'div' and class_attr == 'message' and pos == 'start' end_of_thread = tag == 'div' and 'thread' in class_attr and pos == 'end' if start_of_message and not self.messages_started: self.messages_started = True elif tag == "span" and pos == "end": if "user" in class_attr: self.current_sender = self.name_resolver.resolve(e.text) elif "meta" in class_attr: self.current_timestamp =\ parse_timestamp(e.text, self.use_utc, self.timezone_hints) elif tag == 'p' and pos == 'end': # This is only necessary because of accidental double <p> nesting on # Facebook's end. Clearly, QA and testing is one of Facebook's strengths ;) if not self.current_text: self.current_text = e.text.strip() if e.text else '' elif tag == 'img' and pos == 'start': self.current_text = '(image reference: {})'.format(e.attrib['src']) elif (start_of_message or end_of_thread) and self.messages_started: if not self.current_timestamp: # This is the typical error when the new Facebook format is # used with the legacy parser. raise UnsuitableParserError if not self.current_sender: if not self.no_sender_warning_status: sys.stderr.write( "\rWARNING: The sender was missing in one or more parsed messages. " "This is an error on Facebook's end that unfortunately cannot be " "recovered from. Some or all messages in the output may show the " "sender as 'Unknown' within each thread.\n") self.no_sender_warning_status = True self.current_sender = "Unknown" cm = ChatMessage(timestamp=self.current_timestamp, sender=self.current_sender, content=self.current_text or '', seq_num=self.seq_num) self.messages += [cm] self.seq_num -= 1 self.current_sender, self.current_timestamp, self.current_text = None, None, None return end_of_thread
def _process_element(self, pos, e)
Parses an incoming HTML element/node for data. pos -- the part of the element being parsed (start/end) e -- the element being parsed
4.270434
4.283091
0.997045
if not self.thread_filter: return True if len(participants) != len(self.thread_filter): return False participants = [[p.lower()] + p.lower().split(" ") for p in participants] matches = defaultdict(set) for e, p in enumerate(participants): for f in self.thread_filter: if f in p: matches[f].add(e) matched = set() for f in matches: if len(matches[f]) == 0: return False matched |= matches[f] return len(matched) == len(participants)
def should_record_thread(self, participants)
Determines if the thread should be parsed based on the participants and the filter given. For example, if the filter states ['jack', 'billy joe'], then only threads with exactly two participants (excluding the owner of the chat history) containing someone with the first or last name 'Jack' and someone named 'Billy Joel' will be included. Any of the following would match that criteria: - Jack Stevenson, Billy Joel - Billy Joel, Jack Stevens - Jack Jenson, Billy Joel - Jack Jack, Billy Joel participants -- the participants of the thread (excluding the history owner)
2.713082
2.663224
1.018721
# Very rarely threads may lack information on who the # participants are. We will consider those threads corrupted # and skip them. participants_text = _truncate(', '.join(participants), 60) if participants: skip_thread = not self.should_record_thread(participants) participants_text = yellow("[%s]" % participants_text) else: participants_text = "unknown participants" skip_thread = True if skip_thread: line = "\rSkipping chat thread with %s..." % \ yellow(participants_text) else: participants_key = ", ".join(participants) if participants_key in self.chat_threads: thread_current_len = len(self.chat_threads[participants_key]) line = "\rContinuing chat thread with %s %s..." \ % (yellow(participants_text), magenta("<@%d messages>" % thread_current_len)) else: line = "\rDiscovered chat thread with %s..." \ % yellow(participants_text) if self.progress_output: sys.stderr.write(line.ljust(self.last_line_len)) sys.stderr.flush() self.last_line_len = len(line) parser = ChatThreadParser( element_iter, self.timezone_hints, self.use_utc, self.name_resolver, self.no_sender_warning, self.seq_num) if skip_thread: if require_flush: parser.skip() else: self.no_sender_warning, thread = parser.parse(participants) return thread
def parse_thread(self, participants, element_iter, require_flush)
Parses a thread with appropriate CLI feedback. :param participants: The participants in this thread. :param element_iter: The XML iterator to parse the data from. :param require_flush: Whether the iterator needs to be flushed if it is determined that the thread should be skipped. :return: A `ChatThread` object if not skipped, otherwise `None`.
4.642066
4.487044
1.034549
# If progress output was being written, clear it from the screen. if self.progress_output: sys.stderr.write("\r".ljust(self.last_line_len)) sys.stderr.write("\r") sys.stderr.flush()
def _clear_output(self)
Clears progress output (if any) that was written to the screen.
5.573839
4.176919
1.334438
# Cast to str to ensure not unicode under Python 2, as the parser # doesn't like that. parser = XMLParser(encoding=str('UTF-8')) element_iter = ET.iterparse(self.handle, events=("start", "end"), parser=parser) for pos, element in element_iter: tag, class_attr = _tag_and_class_attr(element) if tag == "h1" and pos == "end": if not self.user: self.user = element.text.strip() elif tag == "div" and "thread" in class_attr and pos == "start": participants = self.parse_participants(element) thread = self.parse_thread(participants, element_iter, True) self.save_thread(thread)
def parse_impl(self)
Parses the HTML content as a stream. This is far less memory intensive than loading the entire HTML file into memory, like BeautifulSoup does.
4.948129
4.717462
1.048897
with colorize_output(nocolor): try: chat_history = _process_history( path=path, thread=thread, timezones=timezones, utc=utc, noprogress=noprogress, resolve=resolve) except ProcessingFailure: return if directory: set_all_color(enabled=False) write(fmt, chat_history, directory or sys.stdout)
def messages(path, thread, fmt, nocolor, timezones, utc, noprogress, resolve, directory)
Conversion of Facebook chat history.
5.07418
5.089791
0.996933
with colorize_output(nocolor): try: chat_history = _process_history( path=path, thread='', timezones=timezones, utc=utc, noprogress=noprogress, resolve=resolve) except ProcessingFailure: return statistics = ChatHistoryStatistics( chat_history, most_common=None if most_common < 0 else most_common) if fmt == 'text': statistics.write_text(sys.stdout, -1 if length < 0 else length) elif fmt == 'json': statistics.write_json(sys.stdout) elif fmt == 'pretty-json': statistics.write_json(sys.stdout, pretty=True) elif fmt == 'yaml': statistics.write_yaml(sys.stdout)
def stats(path, fmt, nocolor, timezones, utc, noprogress, most_common, resolve, length)
Analysis of Facebook chat history.
3.039294
2.934081
1.035859
original_stdout = sys.stdout original_stderr = sys.stderr init(strip=disabled) if stream != original_stdout: sys.stdout = original_stdout sys.stderr = BinaryStreamWrapper(stream, sys.stderr) if stream != original_stderr: sys.stderr = original_stderr sys.stdout = BinaryStreamWrapper(stream, sys.stdout)
def set_stream_color(stream, disabled)
Remember what our original streams were so that we can colorize them separately, which colorama doesn't seem to natively support.
3.760164
3.282047
1.145676
resp = self._session.get( 'https://www.facebook.com/%s' % facebook_id, allow_redirects=True, timeout=10 ) # No point in trying to get this using BeautifulSoup. The HTML here # is the very epitome of what it is to be invalid... m = _MANUAL_NAME_MATCHER.search(resp.text) if m: name = m.group(1) else: name = facebook_id_string self._cached_profiles[facebook_id] = name return name
def _manual_lookup(self, facebook_id, facebook_id_string)
People who we have not communicated with in a long time will not appear in the look-ahead cache that Facebook keeps. We must manually resolve them. :param facebook_id: Profile ID of the user to lookup. :return:
5.34867
5.572765
0.959787
global FACEBOOK_TIMESTAMP_FORMATS timestamp_string, offset = raw_timestamp.rsplit(" ", 1) if "UTC+" in offset or "UTC-" in offset: if offset[3] == '-': offset = [-1 * int(x) for x in offset[4:].split(':')] else: offset = [int(x) for x in offset[4:].split(':')] else: offset_hint = hints.get(offset, None) if not offset_hint: if offset not in TIMEZONE_MAP: raise UnexpectedTimeFormatError(raw_timestamp) elif len(TIMEZONE_MAP[offset]) > 1: raise AmbiguousTimeZoneError(offset, TIMEZONE_MAP[offset]) offset = list(TIMEZONE_MAP[offset].keys())[0][:2] else: offset = offset_hint if len(offset) == 1: # Timezones without minute offset may be formatted # as UTC+X (e.g UTC+8) offset += [0] delta = dt_timedelta(hours=offset[0], minutes=offset[1]) # Facebook changes the format depending on whether the user is using # 12-hour or 24-hour clock settings. for number, date_parser in enumerate(_LOCALIZED_DATE_PARSERS): timestamp = date_parser.parse(timestamp_string) if timestamp is None: continue # Re-orient the list to ensure that the one that worked is tried first next time. if number > 0: del FACEBOOK_TIMESTAMP_FORMATS[number] FACEBOOK_TIMESTAMP_FORMATS = [date_parser] + FACEBOOK_TIMESTAMP_FORMATS break else: raise UnexpectedTimeFormatError(raw_timestamp) if use_utc: timestamp -= delta return timestamp.replace(tzinfo=pytz.utc) else: return timestamp.replace(tzinfo=TzInfoByOffset(delta))
def parse_timestamp(raw_timestamp, use_utc, hints)
Facebook is highly inconsistent with their timezone formatting. Sometimes it's in UTC+/-HH:MM form, and other times its in the ambiguous PST, PDT. etc format. We have to handle the ambiguity by asking for cues from the user. raw_timestamp -- The timestamp string to parse and convert to UTC.
3.758707
3.689757
1.018687
# Verify params if not isinstance(name, str) or (not name): raise TypeError("invalid name: %r" % name) if not issubclass(base_class, Component): raise TypeError("invalid base_class: %r, must be a %r subclass" % (base_class, Component)) def decorator(cls): # --- Verify # Can only be registered once if base_class in exporter_index[name]: raise TypeError("'%s' exporter type %r has already been registered" % ( name, base_class )) # Verify class hierarchy will not conflict # (so you can't have an exporter for a Component, and a Part. must be # an Assembly, and a Part, respectively) for key in exporter_index[name].keys(): if issubclass(key, base_class) or issubclass(base_class, key): raise TypeError("'%s' exporter type %r is in conflict with %r" % ( name, base_class, key, )) # --- Index exporter_index[name][base_class] = cls return cls return decorator
def register_exporter(name, base_class)
Register an exporter to use for a :class:`Part <cqparts.Part>`, :class:`Assembly <cqparts.Assembly>`, or both (with :class:`Component <cqparts.Component>`). Registration is necessary to use with :meth:`Component.exporter() <cqparts.Component.exporter>`. :param name: name (or 'key') of exporter :type name: :class:`str` :param base_class: class of :class:`Component <cqparts.Component>` to export :type base_class: :class:`type` .. doctest:: >>> from cqparts import Part >>> from cqparts.codec import Exporter, register_exporter >>> @register_exporter('my_type', Part) ... class MyExporter(Exporter): ... def __call__(self, filename='out.mytype'): ... print("export %r to %s" % (self.obj, filename)) >>> from cqparts_misc.basic.primatives import Sphere >>> thing = Sphere(radius=5) >>> thing.exporter('my_type')('some-file.mytype') export <Sphere: radius=5.0> to some-file.mytype
3.831322
4.010418
0.955342
if name not in exporter_index: raise TypeError( ("exporter type '%s' is not registered: " % name) + ("registered types: %r" % sorted(exporter_index.keys())) ) for base_class in exporter_index[name]: if isinstance(obj, base_class): return exporter_index[name][base_class](obj) raise TypeError("exporter type '%s' for a %r is not registered" % ( name, type(obj) ))
def get_exporter(obj, name)
Get an exporter for the :param obj: object to export :type obj: :class:`Component <cqparts.Component>` :param name: registered name of exporter :type name: :class:`str` :return: an exporter instance of the given type :rtype: :class:`Exporter` :raises TypeError: if exporter cannot be found
3.170455
3.265628
0.970856
if name not in importer_index: raise TypeError( ("importer type '%s' is not registered: " % name) + ("registered types: %r" % sorted(importer_index.keys())) ) for base_class in importer_index[name]: if issubclass(cls, base_class): return importer_index[name][base_class](cls) raise TypeError("importer type '%s' for a %r is not registered" % ( name, cls ))
def get_importer(cls, name)
Get an importer for the given registered type. :param cls: class to import :type cls: :class:`type` :param name: registered name of importer :type name: :class:`str` :return: an importer instance of the given type :rtype: :class:`Importer` :raises TypeError: if importer cannot be found
3.386106
3.337271
1.014633
# Check if page is out of range no_more_products = re.search( r'No matching products were found', response.css('div.paged-results').extract_first(), flags=re.I ) if no_more_products: pass # no more pages to populate, stop scraping else: # Scrape products list for product in response.css('article.product-list__item'): product_url = product.css('a::attr("href")').extract_first() yield response.follow(product_url, self.parse_detail) (base, params) = split_url(response.url) params.update({'page': int(params.get('page', '1')) + 1}) next_page_url = join_url(base, params) self.logger.info(next_page_url) yield response.follow(next_page_url, self.parse)
def parse(self, response)
Parse pagenated list of products
3.286917
3.152157
1.042752
# Product Information (a start) product_data = { 'url': response.url, 'name': response.css('div.page-title h1::text').extract_first(), } # Inventory Number inventory_number = re.search( r'(?P<inv_num>\d+)$', response.css('span.product-in::text').extract_first(), ).group('inv_num') product_data.update({'in': inventory_number}) # Specifications (arbitrary key:value pairs) specs_table = response.css('#tab-specs dl') for row in specs_table.css('div.spec-row'): keys = row.css('dt::text').extract() values = row.css('dd::text').extract() product_data.update({ key: value for (key, value) in zip(keys, values) }) self.logger.info(product_data['name']) yield product_data
def parse_detail(self, response)
Parse individual product's detail
3.105494
3.140933
0.988717
if coord_sys is None: coord_sys = CoordSystem() # default # Verify list contains constraints for constraint in constraints: if not isinstance(constraint, Constraint): raise ValueError("{!r} is not a constraint".format(constraint)) solved_count = 0 indexed = list(constraints) # Continue running solver until no solution is found while indexed: indexes_solved = [] for (i, constraint) in enumerate(indexed): # Fixed if isinstance(constraint, Fixed): indexes_solved.append(i) yield ( constraint.mate.component, coord_sys + constraint.world_coords + (CoordSystem() - constraint.mate.local_coords) ) # Coincident elif isinstance(constraint, Coincident): try: relative_to = constraint.to_mate.world_coords except ValueError: relative_to = None if relative_to is not None: indexes_solved.append(i) # note: relative_to are world coordinates; adding coord_sys is not necessary yield ( constraint.mate.component, relative_to + (CoordSystem() - constraint.mate.local_coords) ) if not indexes_solved: # no solutions found # At least 1 solution must be found each iteration. # if not, we'll just be looping forever. break else: # remove constraints from indexed list (so they're not solved twice) for j in reversed(indexes_solved): del indexed[j] if indexed: raise ValueError("not all constraints could be solved")
def solver(constraints, coord_sys=None)
Solve constraints. Solutions pair :class:`Constraint <cqparts.constraint.Constraint>` instances with their suitable :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` world coordinates. :param constraints: constraints to solve :type constraints: iterable of :class:`Constraint <cqparts.constraint.Constraint>` :param coord_sys: coordinate system to offset solutions (default: no offset) :type coord_sys: :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` :return: generator of (:class:`Component <cqparts.Component>`, :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>`) tuples.
4.448999
4.138938
1.074913
if isinstance(solid_in, cadquery.Solid): return solid_in elif isinstance(solid_in, cadquery.CQ): return solid_in.val() raise CastingError( "Cannot cast object type of {!r} to a solid".format(solid_in) )
def solid(solid_in)
:return: cadquery.Solid instance
3.530418
3.200902
1.102945
if isinstance(vect_in, cadquery.Vector): return vect_in elif isinstance(vect_in, (tuple, list)): return cadquery.Vector(vect_in) raise CastingError( "Cannot cast object type of {!r} to a vector".format(vect_in) )
def vector(vect_in)
:return: cadquery.Vector instance
3.28914
2.815633
1.168171
return cadquery.Workplane('XY') \ .circle(self.access_diameter / 2) \ .extrude(self.access_height)
def make_cutter(self)
Create solid to subtract from material to make way for the fastener's head (just the head)
4.73715
3.968466
1.193698
# cast version version = LooseVersion(version_str) for (test_ver, classifier) in reversed(sorted(VERSION_CLASSIFIER_MAP, key=lambda x: x[0])): if version >= test_ver: return classifier raise ValueError("could not find valid 'Development Status' classifier for v{}".format(version_str))
def version_classifier(version_str)
Verify version consistency: version number must correspond to the correct "Development Status" classifier :raises: ValueError if error found, but ideally this function does nothing
5.497758
4.401357
1.249105
" top of the stator" return Mate(self, CoordSystem( origin=(0, 0, self.length/2), xDir=(0, 1, 0), normal=(0, 0, 1) ))
def mate_top(self)
top of the stator
5.574539
4.253803
1.310484
" bottom of the stator" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(1, 0, 0), normal=(0, 0, -1) ))
def mate_bottom(self)
bottom of the stator
5.183771
4.176589
1.241149
" return mount points" wp = cq.Workplane("XY") h = wp.rect(self.hole_spacing,self.hole_spacing ,forConstruction=True).vertices() return h.objects
def mount_points(self)
return mount points
15.137451
15.737667
0.961861
" shaft cutout " stepper_shaft = self.components['shaft'] top = self.components['topcap'] local_obj = top.local_obj local_obj = local_obj.cut(stepper_shaft.get_cutout(clearance=0.5))
def apply_cutout(self)
shaft cutout
9.77994
8.433398
1.159668
param_names = set( k for (k, v) in cls.__dict__.items() if isinstance(v, Parameter) ) for parent in cls.__bases__: if hasattr(parent, 'class_param_names'): param_names |= parent.class_param_names(hidden=hidden) if not hidden: param_names = set(n for n in param_names if not n.startswith('_')) return param_names
def class_param_names(cls, hidden=True)
Return the names of all class parameters. :param hidden: if ``False``, excludes parameters with a ``_`` prefix. :type hidden: :class:`bool` :return: set of parameter names :rtype: :class:`set`
2.131265
2.430652
0.876828
param_names = cls.class_param_names(hidden=hidden) return dict( (name, getattr(cls, name)) for name in param_names )
def class_params(cls, hidden=True)
Gets all class parameters, and their :class:`Parameter` instances. :return: dict of the form: ``{<name>: <Parameter instance>, ... }`` :rtype: :class:`dict` .. note:: The :class:`Parameter` instances returned do not have a value, only a default value. To get a list of an **instance's** parameters and values, use :meth:`params` instead.
3.081489
4.123779
0.747249
param_names = self.class_param_names(hidden=hidden) return dict( (name, getattr(self, name)) for name in param_names )
def params(self, hidden=True)
Gets all instance parameters, and their *cast* values. :return: dict of the form: ``{<name>: <value>, ... }`` :rtype: :class:`dict`
3.906739
4.778984
0.817483
return { # Encode library information (future-proofing) 'lib': { 'name': 'cqparts', 'version': __version__, }, # class & name record, for automated import when decoding 'class': { 'module': type(self).__module__, 'name': type(self).__name__, }, 'params': self.serialize_parameters(), }
def serialize(self)
Encode a :class:`ParametricObject` instance to an object that can be encoded by the :mod:`json` module. :return: a dict of the format: :rtype: :class:`dict` :: { 'lib': { # library information 'name': 'cqparts', 'version': '0.1.0', }, 'class': { # importable class 'module': 'yourpartslib.submodule', # module containing class 'name': 'AwesomeThing', # class being serialized }, 'params': { # serialized parameters of AwesomeThing 'x': 10, 'y': 20, } } value of ``params`` key comes from :meth:`serialize_parameters` .. important:: Serialize pulls the class name from the classes ``__name__`` parameter. This must be the same name of the object holding the class data, or the instance cannot be re-instantiated by :meth:`deserialize`. **Examples (good / bad)** .. doctest:: >>> from cqparts.params import ParametricObject, Int >>> # GOOD Example >>> class A(ParametricObject): ... x = Int(10) >>> A().serialize()['class']['name'] 'A' >>> # BAD Example >>> B = type('Foo', (ParametricObject,), {'x': Int(10)}) >>> B().serialize()['class']['name'] # doctest: +SKIP 'Foo' In the second example, the classes import name is expected to be ``B``. But instead, the *name* ``Foo`` is recorded. This mismatch will be irreconcilable when attempting to :meth:`deserialize`.
8.65287
5.586523
1.548883
# Get parameter data class_params = self.class_params() instance_params = self.params() # Serialize each parameter serialized = {} for name in class_params.keys(): param = class_params[name] value = instance_params[name] serialized[name] = param.serialize(value) return serialized
def serialize_parameters(self)
Get the parameter data in its serialized form. Data is serialized by each parameter's :meth:`Parameter.serialize` implementation. :return: serialized parameter data in the form: ``{<name>: <serial data>, ...}`` :rtype: :class:`dict`
3.472149
3.313366
1.047922
# Import module & get class try: module = import_module(data.get('class').get('module')) cls = getattr(module, data.get('class').get('name')) except ImportError: raise ImportError("No module named: %r" % data.get('class').get('module')) except AttributeError: raise ImportError("module %r does not contain class %r" % ( data.get('class').get('module'), data.get('class').get('name') )) # Deserialize parameters class_params = cls.class_params(hidden=True) params = dict( (name, class_params[name].deserialize(value)) for (name, value) in data.get('params').items() ) # Instantiate new instance return cls(**params)
def deserialize(data)
Create instance from serial data
2.657076
2.608432
1.018649
def inner(cls): # Add class references to search index class_list.add(cls) for (category, value) in criteria.items(): index[category][value].add(cls) # Retain search criteria _entry = dict((k, set([v])) for (k, v) in criteria.items()) if cls not in class_criteria: class_criteria[cls] = _entry else: for key in _entry.keys(): class_criteria[cls][key] = class_criteria[cls].get(key, set()) | _entry[key] # Return class return cls return inner
def register(**criteria)
class decorator to add :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` to the ``cqparts`` search index: .. testcode:: import cqparts from cqparts.params import * # Created Part or Assembly @cqparts.search.register( type='motor', current_class='dc', part_number='ABC123X', ) class SomeMotor(cqparts.Assembly): shaft_diam = PositiveFloat(5) def make_components(self): return {} # build assembly content motor_class = cqparts.search.find(part_number='ABC123X') motor = motor_class(shaft_diam=6.0) Then use :meth:`find` &/or :meth:`search` to instantiate it. .. warning:: Multiple classes *can* be registered with identical criteria, but should be avoided. If multiple classes share the same criteria, :meth:`find` will never yield the part you want. Try adding unique criteria, such as *make*, *model*, *part number*, *library name*, &/or *author*. To avoid this, learn more in :ref:`tutorial_component-index`.
3.758141
3.909836
0.961202
# Find all parts that match the given criteria results = copy(class_list) # start with full list for (category, value) in criteria.items(): results &= index[category][value] return results
def search(**criteria)
Search registered *component* classes matching the given criteria. :param criteria: search criteria of the form: ``a='1', b='x'`` :return: parts registered with the given criteria :rtype: :class:`set` Will return an empty :class:`set` if nothing is found. :: from cqparts.search import search import cqparts_motors # example of a 3rd party lib # Get all DC motor classes dc_motors = search(type='motor', current_class='dc') # For more complex queries: air_cooled = search(cooling='air') non_aircooled_dcmotors = dc_motors - air_cooled # will be all DC motors that aren't air-cooled
10.586845
13.131239
0.806234
# Find all parts that match the given criteria results = search(**criteria) # error cases if len(results) > 1: raise SearchMultipleFoundError("%i results found" % len(results)) elif not results: raise SearchNoneFoundError("%i results found" % len(results)) # return found Part|Assembly class return results.pop()
def find(**criteria)
Find a single *component* class with the given criteria. Finds classes indexed with :meth:`register` :raises SearchMultipleFoundError: if more than one result found :raises SearchNoneFoundError: if nothing found :: from cqparts.search import find import cqparts_motors # example of a 3rd party lib # get a specific motor class motor_class = find(type='motor', part_number='ABC123X') motor = motor_class(shaft_diameter=6.0)
6.349393
5.652617
1.123266
def decorator(func): def inner(*args, **kwargs): merged_kwargs = copy(common) merged_kwargs.update(kwargs) return func(*args, **merged_kwargs) return inner return decorator
def common_criteria(**common)
Wrap a function to always call with the given ``common`` named parameters. :property common: criteria common to your function call :return: decorator function :rtype: :class:`function` .. doctest:: >>> import cqparts >>> from cqparts.search import register, search, find >>> from cqparts.search import common_criteria >>> # Somebody elses (boring) library may register with... >>> @register(a='one', b='two') ... class BoringThing(cqparts.Part): ... pass >>> # But your library is awesome; only registering with unique criteria... >>> lib_criteria = { ... 'author': 'your_name', ... 'libname': 'awesome_things', ... } >>> awesome_register = common_criteria(**lib_criteria)(register) >>> @awesome_register(a='one', b='two') # identical to BoringThing ... class AwesomeThing(cqparts.Part): ... pass >>> # So lets try a search >>> len(search(a='one', b='two')) # doctest: +SKIP 2 >>> # oops, that returned both classes >>> # To narrow it down, we add something unique: >>> len(search(a='one', b='two', libname='awesome_things')) # finds only yours # doctest: +SKIP 1 >>> # or, we could use common_criteria again... >>> awesome_search = common_criteria(**lib_criteria)(search) >>> awesome_find = common_criteria(**lib_criteria)(find) >>> len(awesome_search(a='one', b='two')) # doctest: +SKIP 1 >>> awesome_find(a='one', b='two').__name__ 'AwesomeThing' A good universal way to apply unique criteria is with .. testcode:: import cadquery, cqparts from cqparts.search import register, common_criteria _register = common_criteria(module=__name__)(register) @_register(shape='cube', scale='unit') class Cube(cqparts.Part): # just an example... def make(self): return cadquery.Workplane('XY').box(1, 1, 1)
2.967277
4.145309
0.715816
# Verify types if not all(isinstance(x, cadquery.BoundBox) for x in bb_list): raise TypeError( "parameters must be cadquery.BoundBox instances: {!r}".format(bb_list) ) if len(bb_list) <= 1: return bb_list[0] # if only 1, nothing to merge; simply return it # Find the smallest bounding box to enclose each of those given min_params = list(min(*vals) for vals in zip( # minimum for each axis *((bb.xmin, bb.ymin, bb.zmin) for bb in bb_list) )) max_params = list(max(*vals) for vals in zip( # maximum for each axis *((bb.xmax, bb.ymax, bb.zmax) for bb in bb_list) )) #__import__('ipdb').set_trace() # Create new object with combined parameters WrappedType = type(bb_list[0].wrapped) # assuming they're all the same wrapped_bb = WrappedType(*(min_params + max_params)) return cadquery.BoundBox(wrapped_bb)
def merge_boundboxes(*bb_list)
Combine bounding boxes to result in a single BoundBox that encloses all of them. :param bb_list: List of bounding boxes :type bb_list: :class:`list` of :class:`cadquery.BoundBox`
3.735316
3.565063
1.047756
return cls( origin=plane.origin.toTuple(), xDir=plane.xDir.toTuple(), normal=plane.zDir.toTuple(), )
def from_plane(cls, plane)
:param plane: cadquery plane instance to base coordinate system on :type plane: :class:`cadquery.Plane` :return: duplicate of the given plane, in this class :rtype: :class:`CoordSystem` usage example: .. doctest:: >>> import cadquery >>> from cqparts.utils.geometry import CoordSystem >>> obj = cadquery.Workplane('XY').circle(1).extrude(5) >>> plane = obj.faces(">Z").workplane().plane >>> isinstance(plane, cadquery.Plane) True >>> coord_sys = CoordSystem.from_plane(plane) >>> isinstance(coord_sys, CoordSystem) True >>> coord_sys.origin.z 5.0
4.123015
4.478142
0.920698
r # Create reference points at origin offset = FreeCAD.Vector(0, 0, 0) x_vertex = FreeCAD.Vector(1, 0, 0) # vertex along +X-axis z_vertex = FreeCAD.Vector(0, 0, 1) # vertex along +Z-axis # Transform reference points offset = matrix.multiply(offset) x_vertex = matrix.multiply(x_vertex) z_vertex = matrix.multiply(z_vertex) # Get axis vectors (relative to offset vertex) x_axis = x_vertex - offset z_axis = z_vertex - offset # Return new instance vect_tuple = lambda v: (v.x, v.y, v.z) return cls( origin=vect_tuple(offset), xDir=vect_tuple(x_axis), normal=vect_tuple(z_axis), )
def from_transform(cls, matrix)
r""" :param matrix: 4x4 3d affine transform matrix :type matrix: :class:`FreeCAD.Matrix` :return: a unit, zero offset coordinate system transformed by the given matrix :rtype: :class:`CoordSystem` Individual rotation & translation matricies are: .. math:: R_z & = \begin{bmatrix} cos(\alpha) & -sin(\alpha) & 0 & 0 \\ sin(\alpha) & cos(\alpha) & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} \qquad & R_y & = \begin{bmatrix} cos(\beta) & 0 & sin(\beta) & 0 \\ 0 & 1 & 0 & 0 \\ -sin(\beta) & 0 & cos(\beta) & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} \\ \\ R_x & = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & cos(\gamma) & -sin(\gamma) & 0 \\ 0 & sin(\gamma) & cos(\gamma) & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} \qquad & T_{\text{xyz}} & = \begin{bmatrix} 1 & 0 & 0 & \delta x \\ 0 & 1 & 0 & \delta y \\ 0 & 0 & 1 & \delta z \\ 0 & 0 & 0 & 1 \end{bmatrix} The ``transform`` is the combination of these: .. math:: transform = T_{\text{xyz}} \cdot R_z \cdot R_y \cdot R_x = \begin{bmatrix} a & b & c & \delta x \\ d & e & f & \delta y \\ g & h & i & \delta z \\ 0 & 0 & 0 & 1 \end{bmatrix} Where: .. math:: a & = cos(\alpha) cos(\beta) \\ b & = cos(\alpha) sin(\beta) sin(\gamma) - sin(\alpha) cos(\gamma) \\ c & = cos(\alpha) sin(\beta) cos(\gamma) + sin(\alpha) sin(\gamma) \\ d & = sin(\alpha) cos(\beta) \\ e & = sin(\alpha) sin(\beta) sin(\gamma) + cos(\alpha) cos(\gamma) \\ f & = sin(\alpha) sin(\beta) cos(\gamma) - cos(\alpha) sin(\gamma) \\ g & = -sin(\beta) \\ h & = cos(\beta) sin(\gamma) \\ i & = cos(\beta) cos(\gamma)
3.173533
3.163812
1.003073
if seed is not None: random.seed(seed) def rand_vect(min, max): return ( random.uniform(min, max), random.uniform(min, max), random.uniform(min, max), ) while True: try: return cls( origin=rand_vect(-span, span), xDir=rand_vect(-1, 1), normal=rand_vect(-1, 1), ) except RuntimeError: # Base.FreeCADError inherits from RuntimeError # Raised if xDir & normal vectors are parallel. # (the chance is very low, but it could happen) continue
def random(cls, span=1, seed=None)
Creates a randomized coordinate system. Useful for confirming that an *assembly* does not rely on its origin coordinate system to remain intact. For example, the :class:`CoordSysIndicator` *assembly* aligns 3 boxes along each of the :math:`XYZ` axes. Positioning it randomly by setting its ``world_coords`` shows that each box is always positioned orthogonally to the other two. .. doctest:: from cqparts_misc.basic.indicators import CoordSysIndicator from cqparts.display import display from cqparts.utils import CoordSystem cs = CoordSysIndicator() cs.world_coords = CoordSystem.random() display(cs) # doctest: +SKIP :param span: origin of return will be :math:`\pm span` per axis :param seed: if supplied, return is psudorandom (repeatable) :type seed: hashable object :return: randomized coordinate system :rtype: :class:`CoordSystem`
4.513255
5.015549
0.899853
from .. import Part def inner(*args, **kwargs): part_class = type(func.__name__, (Part,), { 'make': lambda self: func(*args, **kwargs), }) return part_class() inner.__doc__ = func.__doc__ return inner
def as_part(func)
Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) z = Float(4) def make(self): return cadquery.Workplane('XY').box(self.x, self.y, self.z) box = Box(x=6, y=3, z=1) May also be written as:: import cadquery from cqparts.utils.wrappers import as_part @as_part def make_box(x=1, y=2, z=4): return cadquery.Workplane('XY').box(x, y, z) box = make_box(x=6, y=3, z=1) In both cases, ``box`` is a :class:`Part <cqparts.Part>` instance.
3.511014
4.500966
0.780058
result = self.search(*args, **kwargs) if len(result) == 0: raise SearchNoneFoundError("nothing found") elif len(result) > 1: raise SearchMultipleFoundError("more than one result found") return result[0]
def find(self, *args, **kwargs)
Performs the same action as :meth:`search` but asserts a single result. :return: :raises SearchNoneFoundError: if nothing was found :raises SearchMultipleFoundError: if more than one result is found
3.035281
2.125671
1.427916
# Verify component if not isinstance(obj, Component): raise TypeError("can only add(%r), component is a %r" % ( Component, type(obj) )) # Serialize object obj_data = obj.serialize() # Add to database q = tinydb.Query() if (force or _check_id) and self.items.count(q.id == id): if force: self.items.remove(q.id == id) else: raise ValueError("entry with id '%s' already exists" % (id)) index = self.items.insert({ 'id': id, # must be unique 'criteria': criteria, 'obj': obj_data, }) return index
def add(self, id, obj, criteria={}, force=False, _check_id=True)
Add a :class:`Component <cqparts.Component>` instance to the database. :param id: unique id of entry, can be anything :type id: :class:`str` :param obj: component to be serialized, then added to the catalogue :type obj: :class:`Component <cqparts.Component>` :param criteria: arbitrary search criteria for the entry :type criteria: :class:`dict` :param force: if ``True``, entry is forcefully overwritten if it already exists. Otherwise an exception is raised :type force: :class:`bool` :param _check_id: if ``False``, duplicate ``id`` is not tested :type _check_id: :class:`bool` :raises TypeError: on parameter issues :raises ValueError: if a duplicate db entry is detected (and ``force`` is not set) :return: index of new entry :rtype: :class:`int`
3.764938
3.435478
1.095899
result = self.find(*args, **kwargs) return self.deserialize_item(result)
def get(self, *args, **kwargs)
Combination of :meth:`find` and :meth:`deserialize_item`; the result from :meth:`find` is deserialized and returned. Input is a :mod:`tinydb` query. :return: deserialized object instance :rtype: :class:`Component <cqparts.Component>`
7.368346
3.888218
1.895044
edge = self.result.wire().val().Edges()[0] return edge.Vertices()[0].Center()
def start_point(self)
Start vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector`
32.338856
22.580807
1.432139
coordsys = copy(self.location) coordsys.origin = self.start_point return coordsys
def start_coordsys(self)
Coordinate system at start of effect. All axes are parallel to the original vector evaluation location, with the origin moved to this effect's start point. :return: coordinate system at start of effect :rtype: :class:`CoordSys`
8.651795
8.911314
0.970878
coordsys = copy(self.location) coordsys.origin = self.end_point return coordsys
def end_coordsys(self)
Coordinate system at end of effect. All axes are parallel to the original vector evaluation location, with the origin moved to this effect's end point. :return: coordinate system at end of effect :rtype: :class:`CoordSys`
8.682883
9.155908
0.948337
return self.start_point.sub(self.location.origin).dot(-self.location.zDir)
def origin_displacement(self)
planar distance of start point from self.location along :math:`-Z` axis
17.523947
7.631797
2.296176
# Method: using each solid's bounding box: # - get vector from start to bounding box center # - get vector from bounding box center to any corner # - add the length of both vectors # - return the maximum of these from all solids def max_length_iter(): for part in self.parts: if part.local_obj.findSolid(): bb = part.local_obj.findSolid().BoundingBox() yield abs(bb.center - self.location.origin) + (bb.DiagonalLength / 2) try: return max(max_length_iter()) except ValueError as e: # if iter returns before yielding anything return 0
def max_effect_length(self)
:return: The longest possible effect vector length. :rtype: float In other words, the *radius* of a sphere: - who's center is at ``start``. - all ``parts`` are contained within the sphere.
8.103177
7.712042
1.050717
# Create effect vector (with max length) if not self.max_effect_length: # no effect is possible, return an empty list return [] edge = cadquery.Edge.makeLine( self.location.origin, self.location.origin + (self.location.zDir * -(self.max_effect_length + 1)) # +1 to avoid rounding errors ) wire = cadquery.Wire.assembleEdges([edge]) wp = cadquery.Workplane('XY').newObject([wire]) effect_list = [] # list of self.effect_class instances for part in self.parts: solid = part.world_obj.translate((0, 0, 0)) intersection = solid.intersect(copy(wp)) effect = self.effect_class( location=self.location, part=part, result=intersection, ) if effect: effect_list.append(effect) return sorted(effect_list)
def perform_evaluation(self)
Determine which parts lie along the given vector, and what length :return: effects on the given parts (in order of the distance from the start point) :rtype: list(:class:`VectorEffect`)
5.315223
4.611396
1.152628
disp_env = get_display_environment() if disp_env is None: raise LookupError('valid display environment could not be found') disp_env.display(component, **kwargs)
def display(component, **kwargs)
Display the given component based on the environment it's run from. See :class:`DisplayEnvironment <cqparts.display.environment.DisplayEnvironment>` documentation for more details. :param component: component to display :type component: :class:`Component <cqparts.Component>` Additional parameters may be used by the chosen :class:`DisplayEnvironment <cqparts.display.environment.DisplayEnvironment>`
6.069875
4.898984
1.239007
# Pop named args template = kwargs.pop('template', 'default') doc = kwargs.pop('doc', "render properties") params = {} # Template parameters if template in TEMPLATE: params.update(TEMPLATE[template]) # override template with any additional params params.update(kwargs) # return parameter instance return RenderParam(params, doc=doc)
def render_props(**kwargs)
Return a valid property for cleaner referencing in :class:`Part <cqparts.Part>` child classes. :param template: name of template to use (any of ``TEMPLATE.keys()``) :type template: :class:`str` :param doc: description of parameter for sphinx docs :type doc: :class:`str` :return: render property instance :rtype: :class:`RenderParam` .. doctest:: >>> import cadquery >>> from cqparts.display import render_props >>> import cqparts >>> class Box(cqparts.Part): ... # let's make semi-transparent aluminium (it's a thing!) ... _render = render_props(template='aluminium', alpha=0.8) >>> box = Box() >>> box._render.rgba (192, 192, 192, 0.8) The tools in :mod:`cqparts.display` will use this colour and alpha information to display the part.
8.055707
6.016451
1.338947
self.world_coords = world_coords return workplane.cut(self.world_obj)
def apply(self, workplane, world_coords=CoordSystem())
Application of screwdrive indentation into a workplane (centred on the given world coordinates). :param workplane: workplane with solid to alter :type workplane: :class:`cadquery.Workplane` :param world_coords: coorindate system relative to ``workplane`` to move cutter before it's cut from the ``workplane`` :type world_coords: :class:`CoordSystem`
8.886472
7.849154
1.132157
from ..params import ParametricObject def param_lines(app, obj): params = obj.class_params(hidden=(not hide_private)) # Header doc_lines = [] if params: # only add a header if it's relevant doc_lines += [ ":class:`ParametricObject <cqparts.params.ParametricObject>` constructor parameters:", "", ] for (name, param) in sorted(params.items(), key=lambda x: x[0]): # sort by name doc_lines.append(':param {name}: {doc}'.format( name=name, doc=param._param(), )) doc_lines.append(':type {name}: {doc}'.format( name=name, doc=param._type(), )) return doc_lines # Conditions for running above `param_lines` function (in order) conditions = [ # (all conditions must be met) lambda o: type(o) == type, lambda o: o is not ParametricObject, lambda o: issubclass(o, ParametricObject), ] def callback(app, what, name, obj, options, lines): # sphinx callback # (this method is what actually gets sent to the sphinx runtime) if all(c(obj) for c in conditions): new_lines = param_lines(app, obj) _add_lines(lines, new_lines, prepend=prepend) return callback
def add_parametric_object_params(prepend=False, hide_private=True)
Add :class:`ParametricObject <cqparts.params.ParametricObject>` parameters in a list to the *docstring*. This is only intended to be used with *sphinx autodoc*. In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import add_parametric_object_params def setup(app): app.connect("autodoc-process-docstring", add_parametric_object_params()) Then, when documenting your :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` the :class:`ParametricObject <cqparts.params.ParametricObject>` parameters will also be documented in the output. :param prepend: if True, parameters are added to the beginning of the *docstring*. otherwise, they're appended at the end. :type prepend: :class:`bool` :param hide_private: if True, parameters with a ``_`` prefix are not documented. :type hide_private: :class:`bool`
4.26597
3.947648
1.080636
from ..search import class_criteria from .. import Component COLUMN_INFO = [ # (<title>, <width>, <method>), ('Key', 50, lambda k, v: "``%s``" % k), ('Value', 10, lambda k, v: ', '.join("``%s``" % w for w in v)), ] # note: last column width is irrelevant def param_lines(app, obj): doc_lines = [] criteria = class_criteria.get(obj, {}) row_seperator = ' '.join(('=' * w) for (_, w, _) in COLUMN_INFO) # Header if criteria: # only add a header if it's relevant doc_lines += [ "**Search Criteria:**", "", "This object can be found with :meth:`find() <cqparts.search.find>` ", "and :meth:`search() <cqparts.search.search>` using the following ", "search criteria.", "", row_seperator, ' '.join((("%%-%is" % w) % t) for (t, w, _) in COLUMN_INFO), row_seperator, ] # Add criteria for (key, value) in sorted(criteria.items(), key=lambda x: x[0]): doc_lines.append(' '.join( ("%%-%is" % w) % m(key, value) for (_, w, m) in COLUMN_INFO )) # Footer if criteria: doc_lines += [ row_seperator, "", ] return doc_lines # Conditions for running above `param_lines` function (in order) conditions = [ # (all conditions must be met) lambda o: type(o) == type, lambda o: o is not Component, lambda o: issubclass(o, Component), ] def callback(app, what, name, obj, options, lines): # sphinx callback # (this method is what actually gets sent to the sphinx runtime) if all(c(obj) for c in conditions): new_lines = param_lines(app, obj) _add_lines(lines, new_lines, prepend=prepend) return callback
def add_search_index_criteria(prepend=False)
Add the search criteria used when calling :meth:`register() <cqparts.search.register>` on a :class:`Component <cqparts.Component>` as a table to the *docstring*. This is only intended to be used with *sphinx autodoc*. In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import add_search_index_criteria def setup(app): app.connect("autodoc-process-docstring", add_search_index_criteria()) Then, when documenting your :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` the search criteria will also be documented in the output. :param prepend: if True, table is added to the beginning of the *docstring*. otherwise, it's appended at the end. :type prepend: :class:`bool`
4.446895
3.938601
1.129055
from ..params import Parameter def callback(app, what, name, obj, skip, options): if (what == 'class') and isinstance(obj, Parameter): return True # yes, skip this object return None return callback
def skip_class_parameters()
Can be used with :meth:`add_parametric_object_params`, this removes duplicate variables cluttering the sphinx docs. This is only intended to be used with *sphinx autodoc* In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import skip_class_parameters def setup(app): app.connect("autodoc-skip-member", skip_class_parameters())
7.96408
5.372631
1.482343
last_index = len(items) - 1 for (i, item) in enumerate(items): yield (i == last_index, item)
def indicate_last(items)
iterate through list and indicate which item is the last, intended to assist tree displays of hierarchical content. :return: yielding (<bool>, <item>) where bool is True only on last entry :rtype: generator
3.059236
3.89493
0.785441
initial_path = os.getcwd() os.chdir(path) yield os.chdir(initial_path)
def working_dir(path)
Change working directory within a context:: >>> import os >>> from cqparts.utils import working_dir >>> print(os.getcwd()) /home/myuser/temp >>> with working_dir('..'): ... print(os.getcwd()) ... /home/myuser :param path: working path to use while in context :type path: :class:`str`
2.871968
6.607512
0.434652
if self._profile is None: self._profile = self.build_profile() return self._profile
def profile(self)
Buffered result of :meth:`build_profile`
4.08721
2.53229
1.614037
bb = self.profile.val().BoundingBox() return (bb.xmin, bb.xmax)
def get_radii(self)
Get the inner and outer radii of the thread. :return: (<inner radius>, <outer radius>) :rtype: :class:`tuple` .. note:: Ideally this method is overridden in inheriting classes to mathematically determine the radii. Default action is to generate the profile, then use the bounding box to determine min & max radii. However this method is prone to small numeric error.
25.874237
20.116919
1.286193
(inner_radius, outer_radius) = self.get_radii() radius = (inner_radius + outer_radius) / 2 return cadquery.Workplane('XY') \ .circle(radius).extrude(self.length)
def make_simple(self)
Return a cylinder with the thread's average radius & length. :math:`radius = (inner_radius + outer_radius) / 2`
3.69406
2.431172
1.519456
# get pilothole ratio # note: not done in .initialize_parameters() because this would cause # the thread's profile to be created at initialisation (by default). pilothole_radius = self.pilothole_radius if pilothole_radius is None: (inner_radius, outer_radius) = self.get_radii() pilothole_radius = inner_radius + self.pilothole_ratio * (outer_radius - inner_radius) return cadquery.Workplane('XY') \ .circle(pilothole_radius) \ .extrude(self.length)
def make_pilothole_cutter(self)
Make a solid to subtract from an interfacing solid to bore a pilot-hole.
4.831001
4.790383
1.008479
if self._components is None: self.build(recursive=False) return self._components
def components(self)
Returns full :class:`dict` of :class:`Component` instances, after a successful :meth:`build` :return: dict of named :class:`Component` instances :rtype: :class:`dict` For more information read about the :ref:`parts_assembly-build-cycle` .
6.443737
6.936112
0.929013
if self._constraints is None: self.build(recursive=False) return self._constraints
def constraints(self)
Returns full :class:`list` of :class:`Constraint <cqparts.constraint.Constraint>` instances, after a successful :meth:`build` :return: list of named :class:`Constraint <cqparts.constraint.Constraint>` instances :rtype: :class:`list` For more information read about the :ref:`parts_assembly-build-cycle` .
7.41497
5.943017
1.247678