repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
statueofmike/rtsp
scripts/rtp.py
RtpPacket.decode
def decode(self, byteStream): """Decode the RTP packet.""" self.header = bytearray(byteStream[:HEADER_SIZE]) self.payload = byteStream[HEADER_SIZE:]
python
def decode(self, byteStream): """Decode the RTP packet.""" self.header = bytearray(byteStream[:HEADER_SIZE]) self.payload = byteStream[HEADER_SIZE:]
Decode the RTP packet.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/rtp.py#L40-L43
statueofmike/rtsp
scripts/rtp.py
RtpPacket.timestamp
def timestamp(self): """Return timestamp.""" timestamp = self.header[4] << 24 | self.header[5] << 16 | self.header[6] << 8 | self.header[7] return int(timestamp)
python
def timestamp(self): """Return timestamp.""" timestamp = self.header[4] << 24 | self.header[5] << 16 | self.header[6] << 8 | self.header[7] return int(timestamp)
Return timestamp.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/rtp.py#L54-L57
statueofmike/rtsp
scripts/preview.py
preview_stream
def preview_stream(stream): """ Display stream in an OpenCV window until "q" key is pressed """ # 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)
python
def preview_stream(stream): """ Display stream in an OpenCV window until "q" key is pressed """ # 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)
Display stream in an OpenCV window until "q" key is pressed
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/preview.py#L9-L25
statueofmike/rtsp
scripts/rtsp.py
printrec
def printrec(recst): """ Pretty-printing rtsp strings """ 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")
python
def printrec(recst): """ Pretty-printing rtsp strings """ 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")
Pretty-printing rtsp strings
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/rtsp.py#L40-L50
statueofmike/rtsp
scripts/rtsp.py
get_resources
def get_resources(connection): """ Do an RTSP-DESCRIBE request, then parse out available resources from the response """ 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
python
def get_resources(connection): """ Do an RTSP-DESCRIBE request, then parse out available resources from the response """ 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
Do an RTSP-DESCRIBE request, then parse out available resources from the response
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/rtsp.py#L169-L173
statueofmike/rtsp
scripts/rtsp.py
RTSPConnection.setup
def setup(self,resource_path = "track1"): """ SETUP method defined by RTSP Protocol - https://tools.ietf.org/html/rfc7826#section-13.3 """ 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
python
def setup(self,resource_path = "track1"): """ SETUP method defined by RTSP Protocol - https://tools.ietf.org/html/rfc7826#section-13.3 """ 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
SETUP method defined by RTSP Protocol - https://tools.ietf.org/html/rfc7826#section-13.3
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/rtsp.py#L153-L167
statueofmike/rtsp
scripts/ffmpeg_client.py
FFmpegClient.fetch_image
def fetch_image(self,rtsp_server_uri = _source,timeout_secs = 15): """ Fetch a single frame using FFMPEG. Convert to PIL Image. Slow. """ 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))
python
def fetch_image(self,rtsp_server_uri = _source,timeout_secs = 15): """ Fetch a single frame using FFMPEG. Convert to PIL Image. Slow. """ 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))
Fetch a single frame using FFMPEG. Convert to PIL Image. Slow.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/ffmpeg_client.py#L28-L42
statueofmike/rtsp
scripts/others/rtsp.py
exec_cmd
def exec_cmd(rtsp,cmd): '''根据命令执行操作''' 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)
python
def exec_cmd(rtsp,cmd): '''根据命令执行操作''' 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)
根据命令执行操作
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L293-L320
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._parse_url
def _parse_url(self,url): '''解析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
python
def _parse_url(self,url): '''解析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
解析url,返回(ip,port,target)三元组
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L86-L95
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._connect_server
def _connect_server(self): '''连接服务器,建立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)
python
def _connect_server(self): '''连接服务器,建立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)
连接服务器,建立socket
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L97-L106
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._update_dest_ip
def _update_dest_ip(self): '''如果未指定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)
python
def _update_dest_ip(self): '''如果未指定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)
如果未指定DEST_IP,默认与RTSP使用相同IP
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L108-L113
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient.recv_msg
def recv_msg(self): '''收取一个完整响应消息或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
python
def recv_msg(self): '''收取一个完整响应消息或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
收取一个完整响应消息或ANNOUNCE通知消息
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L115-L133
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._get_content_length
def _get_content_length(self,msg): '''从消息中解析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
python
def _get_content_length(self,msg): '''从消息中解析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
从消息中解析Content-length
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L135-L138
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._process_response
def _process_response(self,msg): '''处理响应消息''' 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
python
def _process_response(self,msg): '''处理响应消息''' 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
处理响应消息
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L145-L163
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._process_announce
def _process_announce(self,msg): '''处理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()
python
def _process_announce(self,msg): '''处理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()
处理ANNOUNCE通知消息
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L165-L175
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._parse_response
def _parse_response(self,msg): '''解析响应消息''' 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
python
def _parse_response(self,msg): '''解析响应消息''' 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
解析响应消息
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L177-L183
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._parse_header_params
def _parse_header_params(self,header_param_lines): '''解析头部参数''' headers = {} for line in header_param_lines: if line.strip(): # 跳过空行 key,val = line.split(':', 1) headers[key.lower()] = val.strip() return headers
python
def _parse_header_params(self,header_param_lines): '''解析头部参数''' headers = {} for line in header_param_lines: if line.strip(): # 跳过空行 key,val = line.split(':', 1) headers[key.lower()] = val.strip() return headers
解析头部参数
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L185-L192
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._parse_track_id
def _parse_track_id(self,sdp): '''从sdp中解析trackID=2形式的字符串''' m = re.search(r'a=control:(?P<trackid>[\w=\d]+)',sdp,re.S) return (m and m.group('trackid')) or ''
python
def _parse_track_id(self,sdp): '''从sdp中解析trackID=2形式的字符串''' m = re.search(r'a=control:(?P<trackid>[\w=\d]+)',sdp,re.S) return (m and m.group('trackid')) or ''
从sdp中解析trackID=2形式的字符串
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L194-L197
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._sendmsg
def _sendmsg(self,method,url,headers): '''发送消息''' 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)
python
def _sendmsg(self,method,url,headers): '''发送消息''' 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)
发送消息
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L203-L219
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient._get_transport_type
def _get_transport_type(self): '''获取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
python
def _get_transport_type(self): '''获取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
获取SETUP时需要的Transport字符串参数
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L221-L233
statueofmike/rtsp
scripts/others/rtsp.py
RTSPClient.send_heart_beat_msg
def send_heart_beat_msg(self): '''定时发送GET_PARAMETER消息保活''' if self.running: self.do_get_parameter() threading.Timer(HEARTBEAT_INTERVAL, self.send_heart_beat_msg).start()
python
def send_heart_beat_msg(self): '''定时发送GET_PARAMETER消息保活''' if self.running: self.do_get_parameter() threading.Timer(HEARTBEAT_INTERVAL, self.send_heart_beat_msg).start()
定时发送GET_PARAMETER消息保活
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rtsp.py#L269-L273
statueofmike/rtsp
scripts/others/rts2.py
Client.setupMovie
def setupMovie(self): """Setup button handler.""" if self.state == self.INIT: self.sendRtspRequest(self.SETUP)
python
def setupMovie(self): """Setup button handler.""" if self.state == self.INIT: self.sendRtspRequest(self.SETUP)
Setup button handler.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.py#L37-L40
statueofmike/rtsp
scripts/others/rts2.py
Client.exitClient
def exitClient(self): """Teardown button handler.""" 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)
python
def exitClient(self): """Teardown button handler.""" 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)
Teardown button handler.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.py#L42-L49
statueofmike/rtsp
scripts/others/rts2.py
Client.pauseMovie
def pauseMovie(self): """Pause button handler.""" if self.state == self.PLAYING: self.sendRtspRequest(self.PAUSE)
python
def pauseMovie(self): """Pause button handler.""" if self.state == self.PLAYING: self.sendRtspRequest(self.PAUSE)
Pause button handler.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.py#L51-L54
statueofmike/rtsp
scripts/others/rts2.py
Client.updateMovie
def updateMovie(self, imageFile): """Update the image file as video frame in the GUI.""" 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
python
def updateMovie(self, imageFile): """Update the image file as video frame in the GUI.""" 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
Update the image file as video frame in the GUI.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.py#L124-L135
statueofmike/rtsp
scripts/others/rts2.py
Client.connectToServer
def connectToServer(self): """Connect to the Server. Start a new RTSP/TCP session.""" 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)
python
def connectToServer(self): """Connect to the Server. Start a new RTSP/TCP session.""" 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)
Connect to the Server. Start a new RTSP/TCP session.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.py#L137-L143
statueofmike/rtsp
scripts/others/rts2.py
Client.sendRtspRequest
def sendRtspRequest(self, requestCode): """Send RTSP request to the server.""" #------------- # 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
python
def sendRtspRequest(self, requestCode): """Send RTSP request to the server.""" #------------- # 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
Send RTSP request to the server.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.py#L145-L214
statueofmike/rtsp
scripts/others/rts2.py
Client.recvRtspReply
def recvRtspReply(self): """Receive RTSP reply from the server.""" 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
python
def recvRtspReply(self): """Receive RTSP reply from the server.""" 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
Receive RTSP reply from the server.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.py#L221-L233
statueofmike/rtsp
scripts/others/rts2.py
Client.parseRtspReply
def parseRtspReply(self, data): print("Parsing Received Rtsp data...") """Parse the RTSP reply from the server.""" 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
python
def parseRtspReply(self, data): print("Parsing Received Rtsp data...") """Parse the RTSP reply from the server.""" 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
Parse the RTSP reply from the server.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.py#L235-L278
statueofmike/rtsp
scripts/others/rts2.py
Client.openRtpPort
def openRtpPort(self): """Open RTP socket binded to a specified port.""" #------------- # 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...')
python
def openRtpPort(self): """Open RTP socket binded to a specified port.""" #------------- # 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...')
Open RTP socket binded to a specified port.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.py#L280-L305
statueofmike/rtsp
rtsp/cvstream.py
PicamVideoFeed.read
def read(self): """https://picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-to-a-pil-image""" 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)
python
def read(self): """https://picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-to-a-pil-image""" 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)
https://picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-to-a-pil-image
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/rtsp/cvstream.py#L24-L30
statueofmike/rtsp
rtsp/cvstream.py
LocalVideoFeed.preview
def preview(self): """ Blocking function. Opens OpenCV window to display stream. """ 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()
python
def preview(self): """ Blocking function. Opens OpenCV window to display stream. """ 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()
Blocking function. Opens OpenCV window to display stream.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/rtsp/cvstream.py#L87-L99
statueofmike/rtsp
scripts/others/rts2.bak.py
Client.createWidgets
def createWidgets(self): """Build GUI.""" # 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)
python
def createWidgets(self): """Build GUI.""" # 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)
Build GUI.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.bak.py#L42-L70
statueofmike/rtsp
scripts/others/rts2.bak.py
Client.playMovie
def playMovie(self): """Play button handler.""" 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)
python
def playMovie(self): """Play button handler.""" 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)
Play button handler.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.bak.py#L92-L100
statueofmike/rtsp
scripts/others/rts2.bak.py
Client.writeFrame
def writeFrame(self, data): """Write the received frame to a temp image file. Return the image file.""" 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
python
def writeFrame(self, data): """Write the received frame to a temp image file. Return the image file.""" 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
Write the received frame to a temp image file. Return the image file.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.bak.py#L141-L158
statueofmike/rtsp
scripts/others/rts2.bak.py
Client.connectToServer
def connectToServer(self): """Connect to the Server. Start a new RTSP/TCP session.""" 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)
python
def connectToServer(self): """Connect to the Server. Start a new RTSP/TCP session.""" 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)
Connect to the Server. Start a new RTSP/TCP session.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.bak.py#L173-L179
statueofmike/rtsp
scripts/others/rts2.bak.py
Client.openRtpPort
def openRtpPort(self): """Open RTP socket binded to a specified port.""" #------------- # 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...')
python
def openRtpPort(self): """Open RTP socket binded to a specified port.""" #------------- # 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...')
Open RTP socket binded to a specified port.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.bak.py#L316-L341
statueofmike/rtsp
scripts/others/rts2.bak.py
Client.handler
def handler(self): """Handler on explicitly closing the GUI window.""" 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)
python
def handler(self): """Handler on explicitly closing the GUI window.""" 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)
Handler on explicitly closing the GUI window.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/rts2.bak.py#L344-L355
statueofmike/rtsp
scripts/others/RtpPacket.py
RtpPacket.encode
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload): """Encode the RTP packet with header fields and payload.""" 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
python
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload): """Encode the RTP packet with header fields and payload.""" 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
Encode the RTP packet with header fields and payload.
https://github.com/statueofmike/rtsp/blob/4816de2da3cc9966122c8511943e6db713052a17/scripts/others/RtpPacket.py#L17-L64
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/parser.py
ChatThreadParser.skip
def skip(self): """ Eats through the input iterator without recording the content. """ 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
python
def skip(self): """ Eats through the input iterator without recording the content. """ 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
Eats through the input iterator without recording the content.
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/parser.py#L131-L138
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/parser.py
ChatThreadParser._process_element
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 """ 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
python
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 """ 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
Parses an incoming HTML element/node for data. pos -- the part of the element being parsed (start/end) e -- the element being parsed
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/parser.py#L140-L192
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/parser.py
MessageHtmlParser.should_record_thread
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) """ 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)
python
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) """ 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)
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)
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/parser.py#L218-L255
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/parser.py
MessageHtmlParser.parse_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`. """ # 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
python
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`. """ # 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
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`.
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/parser.py#L275-L322
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/parser.py
MessageHtmlParser._clear_output
def _clear_output(self): """ Clears progress output (if any) that was written to the screen. """ # 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()
python
def _clear_output(self): """ Clears progress output (if any) that was written to the screen. """ # 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()
Clears progress output (if any) that was written to the screen.
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/parser.py#L365-L373
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/parser.py
LegacyMessageHtmlParser.parse_impl
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. """ # 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)
python
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. """ # 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)
Parses the HTML content as a stream. This is far less memory intensive than loading the entire HTML file into memory, like BeautifulSoup does.
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/parser.py#L385-L404
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/main.py
messages
def messages(path, thread, fmt, nocolor, timezones, utc, noprogress, resolve, directory): """ Conversion of Facebook chat history. """ 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)
python
def messages(path, thread, fmt, nocolor, timezones, utc, noprogress, resolve, directory): """ Conversion of Facebook chat history. """ 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)
Conversion of Facebook chat history.
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/main.py#L174-L187
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/main.py
stats
def stats(path, fmt, nocolor, timezones, utc, noprogress, most_common, resolve, length): """Analysis of Facebook chat history.""" 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)
python
def stats(path, fmt, nocolor, timezones, utc, noprogress, most_common, resolve, length): """Analysis of Facebook chat history.""" 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)
Analysis of Facebook chat history.
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/main.py#L203-L221
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/utils.py
set_stream_color
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. """ 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)
python
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. """ 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)
Remember what our original streams were so that we can colorize them separately, which colorama doesn't seem to natively support.
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/utils.py#L31-L47
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/name_resolver.py
FacebookNameResolver._manual_lookup
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: """ 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
python
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: """ 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
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:
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/name_resolver.py#L125-L146
ownaginatious/fbchat-archive-parser
fbchat_archive_parser/time.py
parse_timestamp
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. """ 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))
python
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. """ 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))
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.
https://github.com/ownaginatious/fbchat-archive-parser/blob/f1e66cea864f1c07b825fc036071f443693231d5/fbchat_archive_parser/time.py#L209-L261
cqparts/cqparts
src/cqparts/codec/__init__.py
register_exporter
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 """ # 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
python
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 """ # 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
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
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/__init__.py#L17-L74
cqparts/cqparts
src/cqparts/codec/__init__.py
get_exporter
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 """ 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) ))
python
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 """ 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) ))
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
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/__init__.py#L77-L101
cqparts/cqparts
src/cqparts/codec/__init__.py
get_importer
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 """ 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 ))
python
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 """ 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 ))
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
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/codec/__init__.py#L146-L170
cqparts/cqparts
src/cqparts_fasteners/catalogue/scripts/bunnings.py
BunningsProductSpider.parse
def parse(self, response): """Parse pagenated list of products""" # 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)
python
def parse(self, response): """Parse pagenated list of products""" # 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)
Parse pagenated list of products
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/catalogue/scripts/bunnings.py#L36-L58
cqparts/cqparts
src/cqparts_fasteners/catalogue/scripts/bunnings.py
BunningsProductSpider.parse_detail
def parse_detail(self, response): """Parse individual product's detail""" # 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
python
def parse_detail(self, response): """Parse individual product's detail""" # 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
Parse individual product's detail
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/catalogue/scripts/bunnings.py#L60-L86
cqparts/cqparts
src/cqparts/constraint/solver.py
solver
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. """ 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")
python
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. """ 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")
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.
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/constraint/solver.py#L7-L72
cqparts/cqparts
src/cqparts_fasteners/utils/_casting.py
solid
def solid(solid_in): """ :return: cadquery.Solid instance """ 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) )
python
def solid(solid_in): """ :return: cadquery.Solid instance """ 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) )
:return: cadquery.Solid instance
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/_casting.py#L17-L28
cqparts/cqparts
src/cqparts_fasteners/utils/_casting.py
vector
def vector(vect_in): """ :return: cadquery.Vector instance """ 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) )
python
def vector(vect_in): """ :return: cadquery.Vector instance """ 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) )
:return: cadquery.Vector instance
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/_casting.py#L31-L42
cqparts/cqparts
src/cqparts_fasteners/solidtypes/fastener_heads/base.py
FastenerHead.make_cutter
def make_cutter(self): """ Create solid to subtract from material to make way for the fastener's head (just the head) """ return cadquery.Workplane('XY') \ .circle(self.access_diameter / 2) \ .extrude(self.access_height)
python
def make_cutter(self): """ Create solid to subtract from material to make way for the fastener's head (just the head) """ return cadquery.Workplane('XY') \ .circle(self.access_diameter / 2) \ .extrude(self.access_height)
Create solid to subtract from material to make way for the fastener's head (just the head)
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/fastener_heads/base.py#L26-L33
cqparts/cqparts
deployment/make-setup.py
version_classifier
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 """ # 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))
python
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 """ # 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))
Verify version consistency: version number must correspond to the correct "Development Status" classifier :raises: ValueError if error found, but ideally this function does nothing
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/deployment/make-setup.py#L121-L134
cqparts/cqparts
src/cqparts_motors/stepper.py
_Stator.mate_top
def mate_top(self): " top of the stator" return Mate(self, CoordSystem( origin=(0, 0, self.length/2), xDir=(0, 1, 0), normal=(0, 0, 1) ))
python
def mate_top(self): " top of the stator" return Mate(self, CoordSystem( origin=(0, 0, self.length/2), xDir=(0, 1, 0), normal=(0, 0, 1) ))
top of the stator
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/stepper.py#L71-L77
cqparts/cqparts
src/cqparts_motors/stepper.py
_Stator.mate_bottom
def mate_bottom(self): " bottom of the stator" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(1, 0, 0), normal=(0, 0, -1) ))
python
def mate_bottom(self): " bottom of the stator" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(1, 0, 0), normal=(0, 0, -1) ))
bottom of the stator
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/stepper.py#L80-L86
cqparts/cqparts
src/cqparts_motors/stepper.py
Stepper.mount_points
def mount_points(self): " return mount points" wp = cq.Workplane("XY") h = wp.rect(self.hole_spacing,self.hole_spacing ,forConstruction=True).vertices() return h.objects
python
def mount_points(self): " return mount points" wp = cq.Workplane("XY") h = wp.rect(self.hole_spacing,self.hole_spacing ,forConstruction=True).vertices() return h.objects
return mount points
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/stepper.py#L154-L159
cqparts/cqparts
src/cqparts_motors/stepper.py
Stepper.apply_cutout
def apply_cutout(self): " 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))
python
def apply_cutout(self): " 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))
shaft cutout
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_motors/stepper.py#L200-L205
cqparts/cqparts
src/cqparts/params/parametric_object.py
ParametricObject.class_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` """ 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
python
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` """ 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
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/parametric_object.py#L81-L100
cqparts/cqparts
src/cqparts/params/parametric_object.py
ParametricObject.class_params
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. """ param_names = cls.class_param_names(hidden=hidden) return dict( (name, getattr(cls, name)) for name in param_names )
python
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. """ param_names = cls.class_param_names(hidden=hidden) return dict( (name, getattr(cls, name)) for name in param_names )
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.
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/parametric_object.py#L103-L123
cqparts/cqparts
src/cqparts/params/parametric_object.py
ParametricObject.params
def params(self, hidden=True): """ Gets all instance parameters, and their *cast* values. :return: dict of the form: ``{<name>: <value>, ... }`` :rtype: :class:`dict` """ param_names = self.class_param_names(hidden=hidden) return dict( (name, getattr(self, name)) for name in param_names )
python
def params(self, hidden=True): """ Gets all instance parameters, and their *cast* values. :return: dict of the form: ``{<name>: <value>, ... }`` :rtype: :class:`dict` """ param_names = self.class_param_names(hidden=hidden) return dict( (name, getattr(self, name)) for name in param_names )
Gets all instance parameters, and their *cast* values. :return: dict of the form: ``{<name>: <value>, ... }`` :rtype: :class:`dict`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/parametric_object.py#L125-L136
cqparts/cqparts
src/cqparts/params/parametric_object.py
ParametricObject.serialize
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`. """ 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(), }
python
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`. """ 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(), }
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`.
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/parametric_object.py#L165-L232
cqparts/cqparts
src/cqparts/params/parametric_object.py
ParametricObject.serialize_parameters
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` """ # 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
python
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` """ # 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
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/parametric_object.py#L234-L255
cqparts/cqparts
src/cqparts/params/parametric_object.py
ParametricObject.deserialize
def deserialize(data): """ Create instance from serial data """ # 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)
python
def deserialize(data): """ Create instance from serial data """ # 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)
Create instance from serial data
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/params/parametric_object.py#L258-L282
cqparts/cqparts
src/cqparts/search.py
register
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`. """ 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
python
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`. """ 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
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`.
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/search.py#L29-L86
cqparts/cqparts
src/cqparts/search.py
search
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 """ # 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
python
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 """ # 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
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
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/search.py#L89-L117
cqparts/cqparts
src/cqparts/search.py
find
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) """ # 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()
python
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) """ # 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()
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)
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/search.py#L120-L148
cqparts/cqparts
src/cqparts/search.py
common_criteria
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) """ def decorator(func): def inner(*args, **kwargs): merged_kwargs = copy(common) merged_kwargs.update(kwargs) return func(*args, **merged_kwargs) return inner return decorator
python
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) """ def decorator(func): def inner(*args, **kwargs): merged_kwargs = copy(common) merged_kwargs.update(kwargs) return func(*args, **merged_kwargs) return inner return decorator
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)
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/search.py#L151-L220
cqparts/cqparts
src/cqparts/utils/geometry.py
merge_boundboxes
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` """ # 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)
python
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` """ # 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)
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/geometry.py#L9-L39
cqparts/cqparts
src/cqparts/utils/geometry.py
CoordSystem.from_plane
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 """ return cls( origin=plane.origin.toTuple(), xDir=plane.xDir.toTuple(), normal=plane.zDir.toTuple(), )
python
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 """ return cls( origin=plane.origin.toTuple(), xDir=plane.xDir.toTuple(), normal=plane.zDir.toTuple(), )
: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
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/geometry.py#L53-L80
cqparts/cqparts
src/cqparts/utils/geometry.py
CoordSystem.from_transform
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) """ # 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), )
python
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) """ # 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), )
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)
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/geometry.py#L83-L163
cqparts/cqparts
src/cqparts/utils/geometry.py
CoordSystem.random
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` """ 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
python
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` """ 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
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/geometry.py#L166-L216
cqparts/cqparts
src/cqparts/utils/wrappers.py
as_part
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. """ 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
python
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. """ 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
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.
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/wrappers.py#L2-L42
cqparts/cqparts
src/cqparts/catalogue/json.py
JSONCatalogue.find
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 """ 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]
python
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 """ 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]
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
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/catalogue/json.py#L109-L125
cqparts/cqparts
src/cqparts/catalogue/json.py
JSONCatalogue.add
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` """ # 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
python
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` """ # 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
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/catalogue/json.py#L128-L174
cqparts/cqparts
src/cqparts/catalogue/json.py
JSONCatalogue.get
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>` """ result = self.find(*args, **kwargs) return self.deserialize_item(result)
python
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>` """ result = self.find(*args, **kwargs) return self.deserialize_item(result)
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>`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/catalogue/json.py#L199-L210
cqparts/cqparts
src/cqparts_fasteners/utils/evaluator.py
VectorEffect.start_point
def start_point(self): """ Start vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector` """ edge = self.result.wire().val().Edges()[0] return edge.Vertices()[0].Center()
python
def start_point(self): """ Start vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector` """ edge = self.result.wire().val().Edges()[0] return edge.Vertices()[0].Center()
Start vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/evaluator.py#L40-L48
cqparts/cqparts
src/cqparts_fasteners/utils/evaluator.py
VectorEffect.start_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` """ coordsys = copy(self.location) coordsys.origin = self.start_point return coordsys
python
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` """ coordsys = copy(self.location) coordsys.origin = self.start_point return coordsys
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/evaluator.py#L51-L63
cqparts/cqparts
src/cqparts_fasteners/utils/evaluator.py
VectorEffect.end_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` """ coordsys = copy(self.location) coordsys.origin = self.end_point return coordsys
python
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` """ coordsys = copy(self.location) coordsys.origin = self.end_point return coordsys
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/evaluator.py#L77-L89
cqparts/cqparts
src/cqparts_fasteners/utils/evaluator.py
VectorEffect.origin_displacement
def origin_displacement(self): """ planar distance of start point from self.location along :math:`-Z` axis """ return self.start_point.sub(self.location.origin).dot(-self.location.zDir)
python
def origin_displacement(self): """ planar distance of start point from self.location along :math:`-Z` axis """ return self.start_point.sub(self.location.origin).dot(-self.location.zDir)
planar distance of start point from self.location along :math:`-Z` axis
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/evaluator.py#L92-L96
cqparts/cqparts
src/cqparts_fasteners/utils/evaluator.py
VectorEvaluator.max_effect_length
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. """ # 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
python
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. """ # 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
: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.
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/evaluator.py#L206-L230
cqparts/cqparts
src/cqparts_fasteners/utils/evaluator.py
VectorEvaluator.perform_evaluation
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`) """ # 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)
python
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`) """ # 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)
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`)
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/utils/evaluator.py#L232-L263
cqparts/cqparts
src/cqparts/display/__init__.py
display
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>` """ disp_env = get_display_environment() if disp_env is None: raise LookupError('valid display environment could not be found') disp_env.display(component, **kwargs)
python
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>` """ disp_env = get_display_environment() if disp_env is None: raise LookupError('valid display environment could not be found') disp_env.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>`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/display/__init__.py#L66-L83
cqparts/cqparts
src/cqparts/display/material.py
render_props
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. """ # 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)
python
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. """ # 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)
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.
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/display/material.py#L191-L233
cqparts/cqparts
src/cqparts_fasteners/solidtypes/screw_drives/base.py
ScrewDrive.apply
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` """ self.world_coords = world_coords return workplane.cut(self.world_obj)
python
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` """ self.world_coords = world_coords return workplane.cut(self.world_obj)
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/screw_drives/base.py#L28-L41
cqparts/cqparts
src/cqparts/utils/sphinx.py
add_parametric_object_params
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` """ 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
python
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` """ 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
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/sphinx.py#L47-L109
cqparts/cqparts
src/cqparts/utils/sphinx.py
add_search_index_criteria
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` """ 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
python
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` """ 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
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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/sphinx.py#L112-L193
cqparts/cqparts
src/cqparts/utils/sphinx.py
skip_class_parameters
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()) """ 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
python
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()) """ 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
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())
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/sphinx.py#L197-L218
cqparts/cqparts
src/cqparts/utils/misc.py
indicate_last
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 """ last_index = len(items) - 1 for (i, item) in enumerate(items): yield (i == last_index, item)
python
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 """ last_index = len(items) - 1 for (i, item) in enumerate(items): yield (i == last_index, item)
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
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/misc.py#L48-L58
cqparts/cqparts
src/cqparts/utils/misc.py
working_dir
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` """ initial_path = os.getcwd() os.chdir(path) yield os.chdir(initial_path)
python
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` """ initial_path = os.getcwd() os.chdir(path) yield os.chdir(initial_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`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/utils/misc.py#L62-L83
cqparts/cqparts
src/cqparts_fasteners/solidtypes/threads/base.py
profile_to_cross_section
def profile_to_cross_section(profile, lefthand=False, start_count=1, min_vertices=20): r""" Converts a thread profile to it's equivalent cross-section. **Profile:** The thread profile contains a single wire along the XZ plane (note: wire will be projected onto the XZ plane; Y-coords will be ignored). The profile is expected to be of 1 thread rotation, so it's height (along the Z-axis) is the thread's "pitch". If start_count > 1, then the profile will effectively be duplicated. The resulting cross-section is designed to be swept along a helical path with a pitch of the thread's "lead" (which is {the height of the given profile} * start_count) **Method:** Each edge of the profile is converted to a bezier spline, aproximating its polar plot equivalent. **Resolution:** (via `min_vertices` parameter) Increasing the number of vertices used to define the bezier will increase the resulting thread's accuracy, but cost more to render. min_vertices may also be expressed as a list to set the number of vertices to set for each wire. where: len(min_vertices) == number of edges in profile **Example** .. doctest:: import cadquery from cqparts_fasteners.solidtypes.threads.base import profile_to_cross_section from Helpers import show # doctest: +SKIP profile = cadquery.Workplane("XZ") \ .moveTo(1, 0) \ .lineTo(2, 1).lineTo(1, 2) \ .wire() cross_section = profile_to_cross_section(profile) show(profile) # doctest: +SKIP show(cross_section) # doctest: +SKIP Will result in: .. image:: /_static/img/solidtypes.threads.base.profile_to_cross_section.01.png :param profile: workplane containing wire of thread profile. :type profile: :class:`cadquery.Workplane` :param lefthand: if True, cross-section is made backwards. :type lefthand: :class:`bool` :param start_count: profile is duplicated this many times. :type start_count: :class:`int` :param min_vertices: int or tuple of the desired resolution. :type min_vertices: :class:`int` or :class:`tuple` :return: workplane with a face ready to be swept into a thread. :rtype: :class:`cadquery.Workplane` :raises TypeError: if a problem is found with the given parameters. :raises ValueError: if ``min_vertices`` is a list with elements not equal to the numbmer of wire edges. """ # verify parameter(s) if not isinstance(profile, cadquery.Workplane): raise TypeError("profile %r must be a %s instance" % (profile, cadquery.Workplane)) if not isinstance(min_vertices, (int, list, tuple)): raise TypeError("min_vertices %r must be an int, list, or tuple" % (min_vertices)) # get wire from Workplane wire = profile.val() # cadquery.Wire if not isinstance(wire, cadquery.Wire): raise TypeError("a valid profile Wire type could not be found in the given Workplane") profile_bb = wire.BoundingBox() pitch = profile_bb.zmax - profile_bb.zmin lead = pitch * start_count # determine vertices count per edge edges = wire.Edges() vertices_count = None if isinstance(min_vertices, int): # evenly spread vertices count along profile wire # (weighted by the edge's length) vertices_count = [ int(ceil(round(e.Length() / wire.Length(), 7) * min_vertices)) for e in edges ] # rounded for desired contrived results # (trade-off: an error of 1 is of no great consequence) else: # min_vertices is defined per edge (already what we want) if len(min_vertices) != len(edges): raise ValueError( "min_vertices list size does not match number of profile edges: " "len(%r) != %i" % (min_vertices, len(edges)) ) vertices_count = min_vertices # Utilities for building cross-section def get_xz(vertex): if isinstance(vertex, cadquery.Vector): vertex = vertex.wrapped # TODO: remove this, it's messy # where isinstance(vertex, FreeCAD.Base.Vector) return (vertex.x, vertex.z) def cart2polar(x, z, z_offset=0): """ Convert cartesian coordinates to polar coordinates. Uses thread's lead height to give full 360deg translation. """ radius = x angle = ((z + z_offset) / lead) * (2 * pi) # radians if not lefthand: angle = -angle return (radius, angle) def transform(vertex, z_offset=0): # where isinstance(vertex, FreeCAD.Base.Vector) """ Transform profile vertex on the XZ plane to it's equivalent on the cross-section's XY plane """ (radius, angle) = cart2polar(*get_xz(vertex), z_offset=z_offset) return (radius * cos(angle), radius * sin(angle)) # Conversion methods def apply_spline(wp, edge, vert_count, z_offset=0): """ Trace along edge and create a spline from the transformed verteces. """ curve = edge.wrapped.Curve # FreeCADPart.Geom* (depending on type) if edge.geomType() == 'CIRCLE': iter_dist = edge.wrapped.ParameterRange[1] / vert_count else: iter_dist = edge.Length() / vert_count points = [] for j in range(vert_count): dist = (j + 1) * iter_dist vert = curve.value(dist) points.append(transform(vert, z_offset)) return wp.spline(points) def apply_arc(wp, edge, z_offset=0): """ Create an arc using edge's midpoint and endpoint. Only intended for use for vertical lines on the given profile. """ return wp.threePointArc( point1=transform(edge.wrapped.valueAt(edge.Length() / 2), z_offset), point2=transform(edge.wrapped.valueAt(edge.Length()), z_offset), ) def apply_radial_line(wp, edge, z_offset=0): """ Create a straight radial line """ return wp.lineTo(*transform(edge.endPoint(), z_offset)) # Build cross-section start_v = edges[0].startPoint().wrapped cross_section = cadquery.Workplane("XY") \ .moveTo(*transform(start_v)) for i in range(start_count): z_offset = i * pitch for (j, edge) in enumerate(wire.Edges()): # where: isinstance(edge, cadquery.Edge) if (edge.geomType() == 'LINE') and (edge.startPoint().x == edge.endPoint().x): # edge is a vertical line, plot a circular arc cross_section = apply_arc(cross_section, edge, z_offset) elif (edge.geomType() == 'LINE') and (edge.startPoint().z == edge.endPoint().z): # edge is a horizontal line, plot a radial line cross_section = apply_radial_line(cross_section, edge, z_offset) else: # create bezier spline along transformed points (default) cross_section = apply_spline(cross_section, edge, vertices_count[j], z_offset) return cross_section.close()
python
def profile_to_cross_section(profile, lefthand=False, start_count=1, min_vertices=20): r""" Converts a thread profile to it's equivalent cross-section. **Profile:** The thread profile contains a single wire along the XZ plane (note: wire will be projected onto the XZ plane; Y-coords will be ignored). The profile is expected to be of 1 thread rotation, so it's height (along the Z-axis) is the thread's "pitch". If start_count > 1, then the profile will effectively be duplicated. The resulting cross-section is designed to be swept along a helical path with a pitch of the thread's "lead" (which is {the height of the given profile} * start_count) **Method:** Each edge of the profile is converted to a bezier spline, aproximating its polar plot equivalent. **Resolution:** (via `min_vertices` parameter) Increasing the number of vertices used to define the bezier will increase the resulting thread's accuracy, but cost more to render. min_vertices may also be expressed as a list to set the number of vertices to set for each wire. where: len(min_vertices) == number of edges in profile **Example** .. doctest:: import cadquery from cqparts_fasteners.solidtypes.threads.base import profile_to_cross_section from Helpers import show # doctest: +SKIP profile = cadquery.Workplane("XZ") \ .moveTo(1, 0) \ .lineTo(2, 1).lineTo(1, 2) \ .wire() cross_section = profile_to_cross_section(profile) show(profile) # doctest: +SKIP show(cross_section) # doctest: +SKIP Will result in: .. image:: /_static/img/solidtypes.threads.base.profile_to_cross_section.01.png :param profile: workplane containing wire of thread profile. :type profile: :class:`cadquery.Workplane` :param lefthand: if True, cross-section is made backwards. :type lefthand: :class:`bool` :param start_count: profile is duplicated this many times. :type start_count: :class:`int` :param min_vertices: int or tuple of the desired resolution. :type min_vertices: :class:`int` or :class:`tuple` :return: workplane with a face ready to be swept into a thread. :rtype: :class:`cadquery.Workplane` :raises TypeError: if a problem is found with the given parameters. :raises ValueError: if ``min_vertices`` is a list with elements not equal to the numbmer of wire edges. """ # verify parameter(s) if not isinstance(profile, cadquery.Workplane): raise TypeError("profile %r must be a %s instance" % (profile, cadquery.Workplane)) if not isinstance(min_vertices, (int, list, tuple)): raise TypeError("min_vertices %r must be an int, list, or tuple" % (min_vertices)) # get wire from Workplane wire = profile.val() # cadquery.Wire if not isinstance(wire, cadquery.Wire): raise TypeError("a valid profile Wire type could not be found in the given Workplane") profile_bb = wire.BoundingBox() pitch = profile_bb.zmax - profile_bb.zmin lead = pitch * start_count # determine vertices count per edge edges = wire.Edges() vertices_count = None if isinstance(min_vertices, int): # evenly spread vertices count along profile wire # (weighted by the edge's length) vertices_count = [ int(ceil(round(e.Length() / wire.Length(), 7) * min_vertices)) for e in edges ] # rounded for desired contrived results # (trade-off: an error of 1 is of no great consequence) else: # min_vertices is defined per edge (already what we want) if len(min_vertices) != len(edges): raise ValueError( "min_vertices list size does not match number of profile edges: " "len(%r) != %i" % (min_vertices, len(edges)) ) vertices_count = min_vertices # Utilities for building cross-section def get_xz(vertex): if isinstance(vertex, cadquery.Vector): vertex = vertex.wrapped # TODO: remove this, it's messy # where isinstance(vertex, FreeCAD.Base.Vector) return (vertex.x, vertex.z) def cart2polar(x, z, z_offset=0): """ Convert cartesian coordinates to polar coordinates. Uses thread's lead height to give full 360deg translation. """ radius = x angle = ((z + z_offset) / lead) * (2 * pi) # radians if not lefthand: angle = -angle return (radius, angle) def transform(vertex, z_offset=0): # where isinstance(vertex, FreeCAD.Base.Vector) """ Transform profile vertex on the XZ plane to it's equivalent on the cross-section's XY plane """ (radius, angle) = cart2polar(*get_xz(vertex), z_offset=z_offset) return (radius * cos(angle), radius * sin(angle)) # Conversion methods def apply_spline(wp, edge, vert_count, z_offset=0): """ Trace along edge and create a spline from the transformed verteces. """ curve = edge.wrapped.Curve # FreeCADPart.Geom* (depending on type) if edge.geomType() == 'CIRCLE': iter_dist = edge.wrapped.ParameterRange[1] / vert_count else: iter_dist = edge.Length() / vert_count points = [] for j in range(vert_count): dist = (j + 1) * iter_dist vert = curve.value(dist) points.append(transform(vert, z_offset)) return wp.spline(points) def apply_arc(wp, edge, z_offset=0): """ Create an arc using edge's midpoint and endpoint. Only intended for use for vertical lines on the given profile. """ return wp.threePointArc( point1=transform(edge.wrapped.valueAt(edge.Length() / 2), z_offset), point2=transform(edge.wrapped.valueAt(edge.Length()), z_offset), ) def apply_radial_line(wp, edge, z_offset=0): """ Create a straight radial line """ return wp.lineTo(*transform(edge.endPoint(), z_offset)) # Build cross-section start_v = edges[0].startPoint().wrapped cross_section = cadquery.Workplane("XY") \ .moveTo(*transform(start_v)) for i in range(start_count): z_offset = i * pitch for (j, edge) in enumerate(wire.Edges()): # where: isinstance(edge, cadquery.Edge) if (edge.geomType() == 'LINE') and (edge.startPoint().x == edge.endPoint().x): # edge is a vertical line, plot a circular arc cross_section = apply_arc(cross_section, edge, z_offset) elif (edge.geomType() == 'LINE') and (edge.startPoint().z == edge.endPoint().z): # edge is a horizontal line, plot a radial line cross_section = apply_radial_line(cross_section, edge, z_offset) else: # create bezier spline along transformed points (default) cross_section = apply_spline(cross_section, edge, vertices_count[j], z_offset) return cross_section.close()
r""" Converts a thread profile to it's equivalent cross-section. **Profile:** The thread profile contains a single wire along the XZ plane (note: wire will be projected onto the XZ plane; Y-coords will be ignored). The profile is expected to be of 1 thread rotation, so it's height (along the Z-axis) is the thread's "pitch". If start_count > 1, then the profile will effectively be duplicated. The resulting cross-section is designed to be swept along a helical path with a pitch of the thread's "lead" (which is {the height of the given profile} * start_count) **Method:** Each edge of the profile is converted to a bezier spline, aproximating its polar plot equivalent. **Resolution:** (via `min_vertices` parameter) Increasing the number of vertices used to define the bezier will increase the resulting thread's accuracy, but cost more to render. min_vertices may also be expressed as a list to set the number of vertices to set for each wire. where: len(min_vertices) == number of edges in profile **Example** .. doctest:: import cadquery from cqparts_fasteners.solidtypes.threads.base import profile_to_cross_section from Helpers import show # doctest: +SKIP profile = cadquery.Workplane("XZ") \ .moveTo(1, 0) \ .lineTo(2, 1).lineTo(1, 2) \ .wire() cross_section = profile_to_cross_section(profile) show(profile) # doctest: +SKIP show(cross_section) # doctest: +SKIP Will result in: .. image:: /_static/img/solidtypes.threads.base.profile_to_cross_section.01.png :param profile: workplane containing wire of thread profile. :type profile: :class:`cadquery.Workplane` :param lefthand: if True, cross-section is made backwards. :type lefthand: :class:`bool` :param start_count: profile is duplicated this many times. :type start_count: :class:`int` :param min_vertices: int or tuple of the desired resolution. :type min_vertices: :class:`int` or :class:`tuple` :return: workplane with a face ready to be swept into a thread. :rtype: :class:`cadquery.Workplane` :raises TypeError: if a problem is found with the given parameters. :raises ValueError: if ``min_vertices`` is a list with elements not equal to the numbmer of wire edges.
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/threads/base.py#L26-L204
cqparts/cqparts
src/cqparts_fasteners/solidtypes/threads/base.py
Thread.profile
def profile(self): """ Buffered result of :meth:`build_profile` """ if self._profile is None: self._profile = self.build_profile() return self._profile
python
def profile(self): """ Buffered result of :meth:`build_profile` """ if self._profile is None: self._profile = self.build_profile() return self._profile
Buffered result of :meth:`build_profile`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/threads/base.py#L298-L304
cqparts/cqparts
src/cqparts_fasteners/solidtypes/threads/base.py
Thread.get_radii
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. """ bb = self.profile.val().BoundingBox() return (bb.xmin, bb.xmax)
python
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. """ bb = self.profile.val().BoundingBox() return (bb.xmin, bb.xmax)
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.
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/threads/base.py#L306-L323
cqparts/cqparts
src/cqparts_fasteners/solidtypes/threads/base.py
Thread.make_simple
def make_simple(self): """ Return a cylinder with the thread's average radius & length. :math:`radius = (inner_radius + outer_radius) / 2` """ (inner_radius, outer_radius) = self.get_radii() radius = (inner_radius + outer_radius) / 2 return cadquery.Workplane('XY') \ .circle(radius).extrude(self.length)
python
def make_simple(self): """ Return a cylinder with the thread's average radius & length. :math:`radius = (inner_radius + outer_radius) / 2` """ (inner_radius, outer_radius) = self.get_radii() radius = (inner_radius + outer_radius) / 2 return cadquery.Workplane('XY') \ .circle(radius).extrude(self.length)
Return a cylinder with the thread's average radius & length. :math:`radius = (inner_radius + outer_radius) / 2`
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_fasteners/solidtypes/threads/base.py#L362-L371