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
|
---|---|---|---|---|---|---|---|
elsampsa/valkka-live | valkka/mvision/tools.py | genH264 | def genH264(infile, outfile, T):
"""Generate H264 stream
Input image, output video file, time in seconds
Example:
::
genH264("/home/sampsa/python3/tests/lprtest/RealImages/IMG_20170308_093511.jpg","testi.mkv", 10)
"""
x264opts="-x264opts keyint=10:min-keyint=10:bframes=0"
h264_dummystream_flavor="-pix_fmt yuv420p -vprofile main"
opts="-vcodec h264 "+h264_dummystream_flavor+" "+x264opts+" -fflags +genpts -r 25 -t "+str(T)
com="ffmpeg -y -loop 1 -fflags +genpts -r 25 -i "+infile+" "+opts+" "+outfile
print(com)
os.system(com) | python | def genH264(infile, outfile, T):
"""Generate H264 stream
Input image, output video file, time in seconds
Example:
::
genH264("/home/sampsa/python3/tests/lprtest/RealImages/IMG_20170308_093511.jpg","testi.mkv", 10)
"""
x264opts="-x264opts keyint=10:min-keyint=10:bframes=0"
h264_dummystream_flavor="-pix_fmt yuv420p -vprofile main"
opts="-vcodec h264 "+h264_dummystream_flavor+" "+x264opts+" -fflags +genpts -r 25 -t "+str(T)
com="ffmpeg -y -loop 1 -fflags +genpts -r 25 -i "+infile+" "+opts+" "+outfile
print(com)
os.system(com) | Generate H264 stream
Input image, output video file, time in seconds
Example:
::
genH264("/home/sampsa/python3/tests/lprtest/RealImages/IMG_20170308_093511.jpg","testi.mkv", 10) | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/tools.py#L31-L49 |
elsampsa/valkka-live | valkka/live/cameralist.py | TreeModel.index | def index(self, row, column, parent):
""" Returns the index of the item in the model specified by the given row, column and parent index.
row, column == int, parent == QModelIndex
"""
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self.root
else:
# So, here we go from QModelIndex to the actual object .. ?
parentItem = parent.internalPointer()
# the only place where a child item is queried
childItem = parentItem.getChild(row)
if childItem:
# return self.createIndex(row, column)
return self.createIndex(row, column, childItem)
"""
# .. that one does not work for PySide 5.12+
TypeError: 'PySide2.QtCore.QAbstractItemModel.createIndex' called with wrong argument types:
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, ServerListItem)
Supported signatures:
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, quintptr = 0)
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, void = nullptr)
"""
else:
return QtCore.QModelIndex() | python | def index(self, row, column, parent):
""" Returns the index of the item in the model specified by the given row, column and parent index.
row, column == int, parent == QModelIndex
"""
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self.root
else:
# So, here we go from QModelIndex to the actual object .. ?
parentItem = parent.internalPointer()
# the only place where a child item is queried
childItem = parentItem.getChild(row)
if childItem:
# return self.createIndex(row, column)
return self.createIndex(row, column, childItem)
"""
# .. that one does not work for PySide 5.12+
TypeError: 'PySide2.QtCore.QAbstractItemModel.createIndex' called with wrong argument types:
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, ServerListItem)
Supported signatures:
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, quintptr = 0)
PySide2.QtCore.QAbstractItemModel.createIndex(int, int, void = nullptr)
"""
else:
return QtCore.QModelIndex() | Returns the index of the item in the model specified by the given row, column and parent index.
row, column == int, parent == QModelIndex | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/cameralist.py#L52-L80 |
elsampsa/valkka-live | valkka/live/cameralist.py | TreeModel.parent | def parent(self, index):
""" Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned.
"""
if not index.isValid():
return QtCore.QModelIndex()
childItem = index.internalPointer()
# the only place where the parent item is queried
parentItem = childItem.getParent()
if parentItem == self.root:
return QtCore.QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem) | python | def parent(self, index):
""" Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned.
"""
if not index.isValid():
return QtCore.QModelIndex()
childItem = index.internalPointer()
# the only place where the parent item is queried
parentItem = childItem.getParent()
if parentItem == self.root:
return QtCore.QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem) | Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned. | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/cameralist.py#L82-L95 |
elsampsa/valkka-live | valkka/live/cameralist.py | TreeModel.columnCount | def columnCount(self, parent):
""" Returns the number of columns for the children of the given parent.
"""
# print("columnCount:",self)
if parent.isValid():
return parent.internalPointer().columnCount()
else:
return self.root.columnCount() | python | def columnCount(self, parent):
""" Returns the number of columns for the children of the given parent.
"""
# print("columnCount:",self)
if parent.isValid():
return parent.internalPointer().columnCount()
else:
return self.root.columnCount() | Returns the number of columns for the children of the given parent. | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/cameralist.py#L97-L104 |
elsampsa/valkka-live | valkka/live/cameralist.py | TreeModel.rowCount | def rowCount(self, parent):
""" Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent.
"""
if parent.column() > 0:
return 0
if not parent.isValid():
parentItem = self.root
else:
parentItem = parent.internalPointer()
return parentItem.childCount() | python | def rowCount(self, parent):
""" Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent.
"""
if parent.column() > 0:
return 0
if not parent.isValid():
parentItem = self.root
else:
parentItem = parent.internalPointer()
return parentItem.childCount() | Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent. | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/cameralist.py#L106-L118 |
elsampsa/valkka-live | valkka/live/cameralist.py | TreeModel.flags | def flags(self, index):
""" Returns the item flags for the given index.
"""
if not index.isValid():
return QtCore.Qt.NoItemFlags
item = index.internalPointer()
# return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable |
# QtCore.Qt.ItemIsDragEnabled
return item.getFlags() | python | def flags(self, index):
""" Returns the item flags for the given index.
"""
if not index.isValid():
return QtCore.Qt.NoItemFlags
item = index.internalPointer()
# return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable |
# QtCore.Qt.ItemIsDragEnabled
return item.getFlags() | Returns the item flags for the given index. | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/cameralist.py#L129-L140 |
Jaymon/pout | pout/interface.py | BaseInterface.full_value | def full_value(self):
"""Returns the full value with the path also (ie, name = value (path))
:returns: String
"""
s = self.name_value()
s += self.path_value()
s += "\n\n"
return s | python | def full_value(self):
"""Returns the full value with the path also (ie, name = value (path))
:returns: String
"""
s = self.name_value()
s += self.path_value()
s += "\n\n"
return s | Returns the full value with the path also (ie, name = value (path))
:returns: String | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L48-L56 |
Jaymon/pout | pout/interface.py | BaseInterface._printstr | def _printstr(self, args, call_info=None):
"""this gets all the args ready to be printed, see self._print()"""
# unicode sandwich, everything printed should be a byte string
s = "\n"
for arg in args:
#s += arg.encode('utf-8', 'pout.replace')
s += arg
if call_info:
s += "({}:{})\n\n".format(self._get_path(call_info['file']), call_info['line'])
return s | python | def _printstr(self, args, call_info=None):
"""this gets all the args ready to be printed, see self._print()"""
# unicode sandwich, everything printed should be a byte string
s = "\n"
for arg in args:
#s += arg.encode('utf-8', 'pout.replace')
s += arg
if call_info:
s += "({}:{})\n\n".format(self._get_path(call_info['file']), call_info['line'])
return s | this gets all the args ready to be printed, see self._print() | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L91-L103 |
Jaymon/pout | pout/interface.py | BaseInterface._str | def _str(self, name, val):
'''
return a string version of name = val that can be printed
example --
_str('foo', 'bar') # foo = bar
name -- string -- the variable name that was passed into one of the public methods
val -- mixed -- the variable at name's value
return -- string
'''
s = ''
v = Value(val)
if name:
logger.debug("{} is type {}".format(name, v.typename))
try:
count = len(val)
s = "{} ({}) = {}".format(name, count, v.string_value())
except (TypeError, KeyError, AttributeError) as e:
logger.info(e, exc_info=True)
s = "{} = {}".format(name, v.string_value())
else:
s = v.string_value()
return s | python | def _str(self, name, val):
'''
return a string version of name = val that can be printed
example --
_str('foo', 'bar') # foo = bar
name -- string -- the variable name that was passed into one of the public methods
val -- mixed -- the variable at name's value
return -- string
'''
s = ''
v = Value(val)
if name:
logger.debug("{} is type {}".format(name, v.typename))
try:
count = len(val)
s = "{} ({}) = {}".format(name, count, v.string_value())
except (TypeError, KeyError, AttributeError) as e:
logger.info(e, exc_info=True)
s = "{} = {}".format(name, v.string_value())
else:
s = v.string_value()
return s | return a string version of name = val that can be printed
example --
_str('foo', 'bar') # foo = bar
name -- string -- the variable name that was passed into one of the public methods
val -- mixed -- the variable at name's value
return -- string | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L106-L134 |
Jaymon/pout | pout/interface.py | LoggingInterface.loggers | def loggers(self):
"""Return all the loggers that should be activated"""
ret = []
if self.logger_name:
if isinstance(self.logger_name, logging.Logger):
ret.append((self.logger_name.name, self.logger_name))
else:
ret.append((self.logger_name, logging.getLogger(self.logger_name)))
else:
ret = list(logging.Logger.manager.loggerDict.items())
ret.append(("root", logging.getLogger()))
return ret | python | def loggers(self):
"""Return all the loggers that should be activated"""
ret = []
if self.logger_name:
if isinstance(self.logger_name, logging.Logger):
ret.append((self.logger_name.name, self.logger_name))
else:
ret.append((self.logger_name, logging.getLogger(self.logger_name)))
else:
ret = list(logging.Logger.manager.loggerDict.items())
ret.append(("root", logging.getLogger()))
return ret | Return all the loggers that should be activated | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L516-L528 |
Jaymon/pout | pout/interface.py | TraceInterface._get_backtrace | def _get_backtrace(self, frames, inspect_packages=False, depth=0):
'''
get a nicely formatted backtrace
since -- 7-6-12
frames -- list -- the frame_tuple frames to format
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
return -- list -- each line will be a nicely formatted entry of the backtrace
'''
calls = []
#count = 1
#for count, f in enumerate(frames[1:], 1):
for count, f in enumerate(frames, 1):
#prev_f = frames[i]
#called_module = inspect.getmodule(prev_f[0]).__name__
#called_func = prev_f[3]
call = self.call_class(f)
s = self._get_call_summary(call, inspect_packages=inspect_packages, index=count)
calls.append(s)
#count += 1
if depth and (count > depth):
break
# reverse the order on return so most recent is on the bottom
return calls[::-1] | python | def _get_backtrace(self, frames, inspect_packages=False, depth=0):
'''
get a nicely formatted backtrace
since -- 7-6-12
frames -- list -- the frame_tuple frames to format
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
return -- list -- each line will be a nicely formatted entry of the backtrace
'''
calls = []
#count = 1
#for count, f in enumerate(frames[1:], 1):
for count, f in enumerate(frames, 1):
#prev_f = frames[i]
#called_module = inspect.getmodule(prev_f[0]).__name__
#called_func = prev_f[3]
call = self.call_class(f)
s = self._get_call_summary(call, inspect_packages=inspect_packages, index=count)
calls.append(s)
#count += 1
if depth and (count > depth):
break
# reverse the order on return so most recent is on the bottom
return calls[::-1] | get a nicely formatted backtrace
since -- 7-6-12
frames -- list -- the frame_tuple frames to format
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
return -- list -- each line will be a nicely formatted entry of the backtrace | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L587-L620 |
Jaymon/pout | pout/interface.py | TraceInterface._get_call_summary | def _get_call_summary(self, call, index=0, inspect_packages=True):
'''
get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_info()
index -- integer -- set to something above 0 if you would like the summary to be numbered
inspect_packages -- boolean -- set to True to get the full format even for system frames
return -- string
'''
call_info = call.info
inspect_regex = re.compile(r'[\\\\/]python\d(?:\.\d+)?', re.I)
# truncate the filepath if it is super long
f = call_info['file']
if len(f) > 75:
f = "{}...{}".format(f[0:30], f[-45:])
if inspect_packages or not inspect_regex.search(call_info['file']):
s = "{}:{}\n\n{}\n\n".format(
f,
call_info['line'],
String(call_info['call']).indent(1)
)
else:
s = "{}:{}\n".format(
f,
call_info['line']
)
if index > 0:
s = "{:02d} - {}".format(index, s)
return s | python | def _get_call_summary(self, call, index=0, inspect_packages=True):
'''
get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_info()
index -- integer -- set to something above 0 if you would like the summary to be numbered
inspect_packages -- boolean -- set to True to get the full format even for system frames
return -- string
'''
call_info = call.info
inspect_regex = re.compile(r'[\\\\/]python\d(?:\.\d+)?', re.I)
# truncate the filepath if it is super long
f = call_info['file']
if len(f) > 75:
f = "{}...{}".format(f[0:30], f[-45:])
if inspect_packages or not inspect_regex.search(call_info['file']):
s = "{}:{}\n\n{}\n\n".format(
f,
call_info['line'],
String(call_info['call']).indent(1)
)
else:
s = "{}:{}\n".format(
f,
call_info['line']
)
if index > 0:
s = "{:02d} - {}".format(index, s)
return s | get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_info()
index -- integer -- set to something above 0 if you would like the summary to be numbered
inspect_packages -- boolean -- set to True to get the full format even for system frames
return -- string | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/interface.py#L622-L664 |
elsampsa/valkka-live | valkka/live/container/mvision.py | MVisionContainer.setDevice | def setDevice(self, device):
"""Sets the video stream
:param device: A rather generic device class. In this case DataModel.RTSPCameraDevice.
"""
self.report("setDevice :", device)
if (self.mvision_process == None):
return
if (not device and not self.device): # None can be passed as an argument when the device has not been set yet
return
if (self.device):
if self.device == device:
self.report("setDevice : same device")
return
if self.filterchain: # there's video already
self.clearDevice()
self.device = device
self.video.setDevice(self.device) # inform the video widget so it can start drags
# ManagedFilterChain.addViewPort accepts ViewPort instance
self.filterchain = self.filterchain_group.get(_id = self.device._id)
if self.filterchain:
self.viewport.setXScreenNum(self.n_xscreen)
self.viewport.setWindowId (int(self.video.winId()))
self.filterchain.addViewPort(self.viewport)
# now the shared mem / semaphore part :
self.shmem_name = self.filterchain.getShmem()
print(self.pre, "setDevice : got shmem name", self.shmem_name)
self.mvision_widget = self.mvision_process.getWidget()
self.mvision_widget.setParent(self.main_widget)
self.main_layout.addWidget(self.mvision_widget)
self.mvision_process.activate(
n_buffer = constant.shmem_n_buffer,
image_dimensions = constant.shmem_image_dimensions,
shmem_name = self.shmem_name
)
self.thread.addProcess(self.mvision_process)
# is there a signal giving the bounding boxes..? let's connect it
if hasattr(self.mvision_process.signals,"bboxes"):
print(self.pre, "setDevice : connecting bboxes signal")
self.mvision_process.signals.bboxes.connect(self.set_bounding_boxes_slot) | python | def setDevice(self, device):
"""Sets the video stream
:param device: A rather generic device class. In this case DataModel.RTSPCameraDevice.
"""
self.report("setDevice :", device)
if (self.mvision_process == None):
return
if (not device and not self.device): # None can be passed as an argument when the device has not been set yet
return
if (self.device):
if self.device == device:
self.report("setDevice : same device")
return
if self.filterchain: # there's video already
self.clearDevice()
self.device = device
self.video.setDevice(self.device) # inform the video widget so it can start drags
# ManagedFilterChain.addViewPort accepts ViewPort instance
self.filterchain = self.filterchain_group.get(_id = self.device._id)
if self.filterchain:
self.viewport.setXScreenNum(self.n_xscreen)
self.viewport.setWindowId (int(self.video.winId()))
self.filterchain.addViewPort(self.viewport)
# now the shared mem / semaphore part :
self.shmem_name = self.filterchain.getShmem()
print(self.pre, "setDevice : got shmem name", self.shmem_name)
self.mvision_widget = self.mvision_process.getWidget()
self.mvision_widget.setParent(self.main_widget)
self.main_layout.addWidget(self.mvision_widget)
self.mvision_process.activate(
n_buffer = constant.shmem_n_buffer,
image_dimensions = constant.shmem_image_dimensions,
shmem_name = self.shmem_name
)
self.thread.addProcess(self.mvision_process)
# is there a signal giving the bounding boxes..? let's connect it
if hasattr(self.mvision_process.signals,"bboxes"):
print(self.pre, "setDevice : connecting bboxes signal")
self.mvision_process.signals.bboxes.connect(self.set_bounding_boxes_slot) | Sets the video stream
:param device: A rather generic device class. In this case DataModel.RTSPCameraDevice. | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/mvision.py#L88-L139 |
elsampsa/valkka-live | valkka/live/container/mvision.py | MVisionContainer.clearDevice | def clearDevice(self):
"""Remove the current stream
"""
print(self.pre, "clearDevice: ")
self.report("clearDevice")
if not self.device:
return
if (self.mvision_process==None):
return
self.filterchain.delViewPort(self.viewport)
self.filterchain.releaseShmem(self.shmem_name)
self.mvision_process.deactivate() # put process back to sleep ..
self.main_layout.removeWidget(self.mvision_widget)
self.filterchain = None
self.device = None
self.video.update() | python | def clearDevice(self):
"""Remove the current stream
"""
print(self.pre, "clearDevice: ")
self.report("clearDevice")
if not self.device:
return
if (self.mvision_process==None):
return
self.filterchain.delViewPort(self.viewport)
self.filterchain.releaseShmem(self.shmem_name)
self.mvision_process.deactivate() # put process back to sleep ..
self.main_layout.removeWidget(self.mvision_widget)
self.filterchain = None
self.device = None
self.video.update() | Remove the current stream | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/mvision.py#L149-L170 |
veripress/veripress | veripress/model/parsers.py | parser | def parser(format_name, ext_names=None):
"""
Decorate a parser class to register it.
:param format_name: standard format name
:param ext_names: supported extension name
"""
def decorator(cls):
format_name_lower = format_name.lower()
if ext_names is None:
_ext_format_mapping[format_name_lower] = format_name_lower
else:
for ext in to_list(ext_names):
_ext_format_mapping[ext.lower()] = format_name_lower
_format_parser_mapping[format_name_lower] = cls()
return cls
return decorator | python | def parser(format_name, ext_names=None):
"""
Decorate a parser class to register it.
:param format_name: standard format name
:param ext_names: supported extension name
"""
def decorator(cls):
format_name_lower = format_name.lower()
if ext_names is None:
_ext_format_mapping[format_name_lower] = format_name_lower
else:
for ext in to_list(ext_names):
_ext_format_mapping[ext.lower()] = format_name_lower
_format_parser_mapping[format_name_lower] = cls()
return cls
return decorator | Decorate a parser class to register it.
:param format_name: standard format name
:param ext_names: supported extension name | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/parsers.py#L100-L118 |
veripress/veripress | veripress/model/parsers.py | Parser.parse_preview | def parse_preview(self, raw_content):
"""
Parse the preview part of the content,
and return the parsed string and whether there is more content or not.
If the preview part is equal to the whole part,
the second element of the returned tuple will be False, else True.
:param raw_content: raw content
:return: tuple(parsed string, whether there is more content or not)
"""
if self._read_more_exp is None:
return self.parse_whole(raw_content), False
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
has_more_content = True
result = sp[0].rstrip()
else:
has_more_content = False
result = raw_content
# since the preview part contains no read_more_sep,
# we can safely use the parse_whole method
return self.parse_whole(result), has_more_content | python | def parse_preview(self, raw_content):
"""
Parse the preview part of the content,
and return the parsed string and whether there is more content or not.
If the preview part is equal to the whole part,
the second element of the returned tuple will be False, else True.
:param raw_content: raw content
:return: tuple(parsed string, whether there is more content or not)
"""
if self._read_more_exp is None:
return self.parse_whole(raw_content), False
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
has_more_content = True
result = sp[0].rstrip()
else:
has_more_content = False
result = raw_content
# since the preview part contains no read_more_sep,
# we can safely use the parse_whole method
return self.parse_whole(result), has_more_content | Parse the preview part of the content,
and return the parsed string and whether there is more content or not.
If the preview part is equal to the whole part,
the second element of the returned tuple will be False, else True.
:param raw_content: raw content
:return: tuple(parsed string, whether there is more content or not) | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/parsers.py#L26-L49 |
veripress/veripress | veripress/model/parsers.py | Parser.remove_read_more_sep | def remove_read_more_sep(self, raw_content):
"""
Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content.
"""
if self._read_more_exp is None:
return raw_content
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
result = '\n\n'.join((sp[0].rstrip(), sp[1].lstrip()))
else:
result = raw_content
return result | python | def remove_read_more_sep(self, raw_content):
"""
Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content.
"""
if self._read_more_exp is None:
return raw_content
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
result = '\n\n'.join((sp[0].rstrip(), sp[1].lstrip()))
else:
result = raw_content
return result | Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content. | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/parsers.py#L58-L71 |
elsampsa/valkka-live | valkka/mvision/yolo3tiny/base.py | MVisionProcess.postActivate_ | def postActivate_(self):
"""Whatever you need to do after creating the shmem client
"""
if (self.requiredGPU_MB(self.required_mb)):
self.analyzer = YoloV3TinyAnalyzer(verbose = self.verbose)
else:
self.warning_message = "WARNING: not enough GPU memory!"
self.analyzer = None | python | def postActivate_(self):
"""Whatever you need to do after creating the shmem client
"""
if (self.requiredGPU_MB(self.required_mb)):
self.analyzer = YoloV3TinyAnalyzer(verbose = self.verbose)
else:
self.warning_message = "WARNING: not enough GPU memory!"
self.analyzer = None | Whatever you need to do after creating the shmem client | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/yolo3tiny/base.py#L71-L78 |
Jaymon/pout | pout/__init__.py | tofile | def tofile(path=""):
"""Instead of printing to a screen print to a file
:Example:
with pout.tofile("/path/to/file.txt"):
# all pout calls in this with block will print to file.txt
pout.v("a string")
pout.b()
pout.h()
:param path: str, a path to the file you want to write to
"""
if not path:
path = os.path.join(os.getcwd(), "{}.txt".format(__name__))
global stream
orig_stream = stream
try:
stream = FileStream(path)
yield stream
finally:
stream = orig_stream | python | def tofile(path=""):
"""Instead of printing to a screen print to a file
:Example:
with pout.tofile("/path/to/file.txt"):
# all pout calls in this with block will print to file.txt
pout.v("a string")
pout.b()
pout.h()
:param path: str, a path to the file you want to write to
"""
if not path:
path = os.path.join(os.getcwd(), "{}.txt".format(__name__))
global stream
orig_stream = stream
try:
stream = FileStream(path)
yield stream
finally:
stream = orig_stream | Instead of printing to a screen print to a file
:Example:
with pout.tofile("/path/to/file.txt"):
# all pout calls in this with block will print to file.txt
pout.v("a string")
pout.b()
pout.h()
:param path: str, a path to the file you want to write to | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L97-L120 |
Jaymon/pout | pout/__init__.py | v | def v(*args, **kwargs):
'''
print the name = values of any passed in variables
this prints out the passed in name, the value, and the file:line where the v()
method was called so you can easily find it and remove it later
example --
foo = 1
bar = [1, 2, 3]
out.v(foo, bar)
""" prints out:
foo = 1
bar =
[
0: 1,
1: 2,
2: 3
]
(/file:line)
"""
*args -- list -- the variables you want to see pretty printed for humans
'''
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance() | python | def v(*args, **kwargs):
'''
print the name = values of any passed in variables
this prints out the passed in name, the value, and the file:line where the v()
method was called so you can easily find it and remove it later
example --
foo = 1
bar = [1, 2, 3]
out.v(foo, bar)
""" prints out:
foo = 1
bar =
[
0: 1,
1: 2,
2: 3
]
(/file:line)
"""
*args -- list -- the variables you want to see pretty printed for humans
'''
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance() | print the name = values of any passed in variables
this prints out the passed in name, the value, and the file:line where the v()
method was called so you can easily find it and remove it later
example --
foo = 1
bar = [1, 2, 3]
out.v(foo, bar)
""" prints out:
foo = 1
bar =
[
0: 1,
1: 2,
2: 3
]
(/file:line)
"""
*args -- list -- the variables you want to see pretty printed for humans | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L124-L155 |
Jaymon/pout | pout/__init__.py | vs | def vs(*args, **kwargs):
"""
exactly like v, but doesn't print variable names or file positions
.. seealso:: ss()
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance.writeline(instance.value()) | python | def vs(*args, **kwargs):
"""
exactly like v, but doesn't print variable names or file positions
.. seealso:: ss()
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance.writeline(instance.value()) | exactly like v, but doesn't print variable names or file positions
.. seealso:: ss() | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L158-L169 |
Jaymon/pout | pout/__init__.py | s | def s(*args, **kwargs):
"""
exactly like v() but returns the string instead of printing it out
since -- 10-15-2015
return -- str
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
return instance.full_value().strip() | python | def s(*args, **kwargs):
"""
exactly like v() but returns the string instead of printing it out
since -- 10-15-2015
return -- str
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
return instance.full_value().strip() | exactly like v() but returns the string instead of printing it out
since -- 10-15-2015
return -- str | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L173-L185 |
Jaymon/pout | pout/__init__.py | ss | def ss(*args, **kwargs):
"""
exactly like s, but doesn't return variable names or file positions (useful for logging)
since -- 10-15-2015
return -- str
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
return instance.value().strip() | python | def ss(*args, **kwargs):
"""
exactly like s, but doesn't return variable names or file positions (useful for logging)
since -- 10-15-2015
return -- str
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
return instance.value().strip() | exactly like s, but doesn't return variable names or file positions (useful for logging)
since -- 10-15-2015
return -- str | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L188-L200 |
Jaymon/pout | pout/__init__.py | r | def r(*args, **kwargs):
"""Similar to pout.v() but gets rid of name and file information so it can be used
in loops and stuff, it will print out where the calls came from at the end of
execution
this just makes it nicer when you're printing a bunch of stuff each iteration
:Example:
for x in range(x):
pout.r(x)
"""
if len(args) <= 0:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = R_CLASS(r, stream, **kwargs)
instance() | python | def r(*args, **kwargs):
"""Similar to pout.v() but gets rid of name and file information so it can be used
in loops and stuff, it will print out where the calls came from at the end of
execution
this just makes it nicer when you're printing a bunch of stuff each iteration
:Example:
for x in range(x):
pout.r(x)
"""
if len(args) <= 0:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = R_CLASS(r, stream, **kwargs)
instance() | Similar to pout.v() but gets rid of name and file information so it can be used
in loops and stuff, it will print out where the calls came from at the end of
execution
this just makes it nicer when you're printing a bunch of stuff each iteration
:Example:
for x in range(x):
pout.r(x) | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L212-L229 |
Jaymon/pout | pout/__init__.py | x | def x(*args, **kwargs):
'''
same as sys.exit(1) but prints out where it was called from before exiting
I just find this really handy for debugging sometimes
since -- 2013-5-9
exit_code -- int -- if you want it something other than 1
'''
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
if args:
instance()
else:
instance.writelines([
'exit at line {}\n'.format(instance.reflect.info["line"]),
instance.path_value()
])
exit_code = 1
sys.exit(exit_code) | python | def x(*args, **kwargs):
'''
same as sys.exit(1) but prints out where it was called from before exiting
I just find this really handy for debugging sometimes
since -- 2013-5-9
exit_code -- int -- if you want it something other than 1
'''
with Reflect.context(args, **kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
if args:
instance()
else:
instance.writelines([
'exit at line {}\n'.format(instance.reflect.info["line"]),
instance.path_value()
])
exit_code = 1
sys.exit(exit_code) | same as sys.exit(1) but prints out where it was called from before exiting
I just find this really handy for debugging sometimes
since -- 2013-5-9
exit_code -- int -- if you want it something other than 1 | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L232-L254 |
Jaymon/pout | pout/__init__.py | h | def h(count=0, **kwargs):
'''
prints "here count"
example --
h(1) # here 1 (/file:line)
h() # here line (/file:line)
count -- integer -- the number you want to put after "here"
'''
with Reflect.context(**kwargs) as r:
kwargs["count"] = count
instance = H_CLASS(r, stream, **kwargs)
instance() | python | def h(count=0, **kwargs):
'''
prints "here count"
example --
h(1) # here 1 (/file:line)
h() # here line (/file:line)
count -- integer -- the number you want to put after "here"
'''
with Reflect.context(**kwargs) as r:
kwargs["count"] = count
instance = H_CLASS(r, stream, **kwargs)
instance() | prints "here count"
example --
h(1) # here 1 (/file:line)
h() # here line (/file:line)
count -- integer -- the number you want to put after "here" | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L257-L270 |
Jaymon/pout | pout/__init__.py | b | def b(*args, **kwargs):
'''
create a big text break, you just kind of have to run it and see
since -- 2013-5-9
*args -- 1 arg = title if string, rows if int
2 args = title, int
3 args = title, int, sep
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
instance = B_CLASS(r, stream, **kwargs)
instance() | python | def b(*args, **kwargs):
'''
create a big text break, you just kind of have to run it and see
since -- 2013-5-9
*args -- 1 arg = title if string, rows if int
2 args = title, int
3 args = title, int, sep
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
instance = B_CLASS(r, stream, **kwargs)
instance() | create a big text break, you just kind of have to run it and see
since -- 2013-5-9
*args -- 1 arg = title if string, rows if int
2 args = title, int
3 args = title, int, sep | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L273-L286 |
Jaymon/pout | pout/__init__.py | c | def c(*args, **kwargs):
'''
kind of like od -c on the command line, basically it dumps each character and info
about that char
since -- 2013-5-9
*args -- tuple -- one or more strings to dump
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
instance = C_CLASS(r, stream, **kwargs)
instance() | python | def c(*args, **kwargs):
'''
kind of like od -c on the command line, basically it dumps each character and info
about that char
since -- 2013-5-9
*args -- tuple -- one or more strings to dump
'''
with Reflect.context(**kwargs) as r:
kwargs["args"] = args
instance = C_CLASS(r, stream, **kwargs)
instance() | kind of like od -c on the command line, basically it dumps each character and info
about that char
since -- 2013-5-9
*args -- tuple -- one or more strings to dump | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L289-L301 |
Jaymon/pout | pout/__init__.py | j | def j(*args, **kwargs):
"""
dump json
since -- 2013-9-10
*args -- tuple -- one or more json strings to dump
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = J_CLASS(r, stream, **kwargs)
instance() | python | def j(*args, **kwargs):
"""
dump json
since -- 2013-9-10
*args -- tuple -- one or more json strings to dump
"""
if not args:
raise ValueError("you didn't pass any arguments to print out")
with Reflect.context(args, **kwargs) as r:
instance = J_CLASS(r, stream, **kwargs)
instance() | dump json
since -- 2013-9-10
*args -- tuple -- one or more json strings to dump | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L304-L317 |
Jaymon/pout | pout/__init__.py | m | def m(name='', **kwargs):
"""
Print out memory usage at this point in time
http://docs.python.org/2/library/resource.html
http://stackoverflow.com/a/15448600/5006
http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended
"""
with Reflect.context(**kwargs) as r:
kwargs["name"] = name
instance = M_CLASS(r, stream, **kwargs)
instance() | python | def m(name='', **kwargs):
"""
Print out memory usage at this point in time
http://docs.python.org/2/library/resource.html
http://stackoverflow.com/a/15448600/5006
http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended
"""
with Reflect.context(**kwargs) as r:
kwargs["name"] = name
instance = M_CLASS(r, stream, **kwargs)
instance() | Print out memory usage at this point in time
http://docs.python.org/2/library/resource.html
http://stackoverflow.com/a/15448600/5006
http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L320-L331 |
Jaymon/pout | pout/__init__.py | p | def p(name="", **kwargs):
'''
really quick and dirty profiling
you start a profile by passing in name, you stop the top profiling by not
passing in a name. You can also call this method using a with statement
This is for when you just want to get a really back of envelope view of
how your fast your code is, super handy, not super accurate
since -- 2013-5-9
example --
p("starting profile")
time.sleep(1)
p() # stop the "starting profile" session
# you can go N levels deep
p("one")
p("two")
time.sleep(0.5)
p() # stop profiling of "two"
time.sleep(0.5)
p() # stop profiling of "one"
with pout.p("three"):
time.sleep(0.5)
name -- string -- pass this in to start a profiling session
return -- context manager
'''
with Reflect.context(**kwargs) as r:
if name:
instance = P_CLASS(r, stream, name, **kwargs)
else:
instance = P_CLASS.pop(r)
instance()
return instance | python | def p(name="", **kwargs):
'''
really quick and dirty profiling
you start a profile by passing in name, you stop the top profiling by not
passing in a name. You can also call this method using a with statement
This is for when you just want to get a really back of envelope view of
how your fast your code is, super handy, not super accurate
since -- 2013-5-9
example --
p("starting profile")
time.sleep(1)
p() # stop the "starting profile" session
# you can go N levels deep
p("one")
p("two")
time.sleep(0.5)
p() # stop profiling of "two"
time.sleep(0.5)
p() # stop profiling of "one"
with pout.p("three"):
time.sleep(0.5)
name -- string -- pass this in to start a profiling session
return -- context manager
'''
with Reflect.context(**kwargs) as r:
if name:
instance = P_CLASS(r, stream, name, **kwargs)
else:
instance = P_CLASS.pop(r)
instance()
return instance | really quick and dirty profiling
you start a profile by passing in name, you stop the top profiling by not
passing in a name. You can also call this method using a with statement
This is for when you just want to get a really back of envelope view of
how your fast your code is, super handy, not super accurate
since -- 2013-5-9
example --
p("starting profile")
time.sleep(1)
p() # stop the "starting profile" session
# you can go N levels deep
p("one")
p("two")
time.sleep(0.5)
p() # stop profiling of "two"
time.sleep(0.5)
p() # stop profiling of "one"
with pout.p("three"):
time.sleep(0.5)
name -- string -- pass this in to start a profiling session
return -- context manager | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L334-L371 |
Jaymon/pout | pout/__init__.py | sleep | def sleep(seconds, **kwargs):
'''
same as time.sleep(seconds) but prints out where it was called before sleeping
and then again after finishing sleeping
I just find this really handy for debugging sometimes
since -- 2017-4-27
:param seconds: float|int, how many seconds to sleep
'''
if seconds <= 0.0:
raise ValueError("Invalid seconds {}".format(seconds))
with Reflect.context(**kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance.writeline("Sleeping {} second{} at {}".format(
seconds,
"s" if seconds != 1.0 else "",
instance.path_value()
))
time.sleep(seconds)
instance.writelines(["...Done Sleeping\n", instance.path_value()]) | python | def sleep(seconds, **kwargs):
'''
same as time.sleep(seconds) but prints out where it was called before sleeping
and then again after finishing sleeping
I just find this really handy for debugging sometimes
since -- 2017-4-27
:param seconds: float|int, how many seconds to sleep
'''
if seconds <= 0.0:
raise ValueError("Invalid seconds {}".format(seconds))
with Reflect.context(**kwargs) as r:
instance = V_CLASS(r, stream, **kwargs)
instance.writeline("Sleeping {} second{} at {}".format(
seconds,
"s" if seconds != 1.0 else "",
instance.path_value()
))
time.sleep(seconds)
instance.writelines(["...Done Sleeping\n", instance.path_value()]) | same as time.sleep(seconds) but prints out where it was called before sleeping
and then again after finishing sleeping
I just find this really handy for debugging sometimes
since -- 2017-4-27
:param seconds: float|int, how many seconds to sleep | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L374-L397 |
Jaymon/pout | pout/__init__.py | t | def t(inspect_packages=False, depth=0, **kwargs):
'''
print a backtrace
since -- 7-6-12
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
'''
#frame = inspect.currentframe()
try:
frames = inspect.stack()
kwargs["frames"] = frames
kwargs["inspect_packages"] = inspect_packages
kwargs["depth"] = depth
with Reflect.context(**kwargs) as r:
instance = T_CLASS(r, stream, **kwargs)
instance()
finally:
del frames | python | def t(inspect_packages=False, depth=0, **kwargs):
'''
print a backtrace
since -- 7-6-12
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack)
'''
#frame = inspect.currentframe()
try:
frames = inspect.stack()
kwargs["frames"] = frames
kwargs["inspect_packages"] = inspect_packages
kwargs["depth"] = depth
with Reflect.context(**kwargs) as r:
instance = T_CLASS(r, stream, **kwargs)
instance()
finally:
del frames | print a backtrace
since -- 7-6-12
inpsect_packages -- boolean -- by default, this only prints code of packages that are not
in the pythonN directories, that cuts out a lot of the noise, set this to True if you
want a full stacktrace
depth -- integer -- how deep you want the stack trace to print (ie, if you only care about
the last three calls, pass in depth=3 so you only get the last 3 rows of the stack) | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L420-L447 |
Jaymon/pout | pout/__init__.py | inject | def inject():
"""Injects pout into the builtins module so it can be called from anywhere without
having to be explicitely imported, this is really just for convenience when
debugging
https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable
"""
try:
from .compat import builtins
module = sys.modules[__name__]
setattr(builtins, __name__, module)
#builtins.pout = pout
except ImportError:
pass | python | def inject():
"""Injects pout into the builtins module so it can be called from anywhere without
having to be explicitely imported, this is really just for convenience when
debugging
https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable
"""
try:
from .compat import builtins
module = sys.modules[__name__]
setattr(builtins, __name__, module)
#builtins.pout = pout
except ImportError:
pass | Injects pout into the builtins module so it can be called from anywhere without
having to be explicitely imported, this is really just for convenience when
debugging
https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L450-L465 |
elsampsa/valkka-live | valkka/live/tools.py | getH264V4l2 | def getH264V4l2(verbose=False):
"""Find all V4l2 cameras with H264 encoding, and returns a list of tuples with ..
(device file, device name), e.g. ("/dev/video2", "HD Pro Webcam C920 (/dev/video2)")
"""
import glob
from subprocess import Popen, PIPE
cams=[]
for device in glob.glob("/sys/class/video4linux/*"):
devname=device.split("/")[-1]
devfile=os.path.join("/dev",devname)
lis=("v4l2-ctl --list-formats -d "+devfile).split()
p = Popen(lis, stdout=PIPE, stderr=PIPE)
# p.communicate()
# print(dir(p))
# print(p.returncode)
# print(p.stderr.read().decode("utf-8"))
st = p.stdout.read().decode("utf-8")
# print(st)
if (st.lower().find("h264")>-1):
namefile=os.path.join(device, "name")
# print(namefile)
f=open(namefile, "r"); name=f.read(); f.close()
fullname = name.strip() + " ("+devname+")"
cams.append((devfile, fullname))
if (verbose):
for cam in cams:
print(cam)
return cams | python | def getH264V4l2(verbose=False):
"""Find all V4l2 cameras with H264 encoding, and returns a list of tuples with ..
(device file, device name), e.g. ("/dev/video2", "HD Pro Webcam C920 (/dev/video2)")
"""
import glob
from subprocess import Popen, PIPE
cams=[]
for device in glob.glob("/sys/class/video4linux/*"):
devname=device.split("/")[-1]
devfile=os.path.join("/dev",devname)
lis=("v4l2-ctl --list-formats -d "+devfile).split()
p = Popen(lis, stdout=PIPE, stderr=PIPE)
# p.communicate()
# print(dir(p))
# print(p.returncode)
# print(p.stderr.read().decode("utf-8"))
st = p.stdout.read().decode("utf-8")
# print(st)
if (st.lower().find("h264")>-1):
namefile=os.path.join(device, "name")
# print(namefile)
f=open(namefile, "r"); name=f.read(); f.close()
fullname = name.strip() + " ("+devname+")"
cams.append((devfile, fullname))
if (verbose):
for cam in cams:
print(cam)
return cams | Find all V4l2 cameras with H264 encoding, and returns a list of tuples with ..
(device file, device name), e.g. ("/dev/video2", "HD Pro Webcam C920 (/dev/video2)") | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/tools.py#L125-L160 |
veripress/veripress | veripress/__init__.py | create_app | def create_app(config_filename, instance_path=None):
"""
Factory function to create Flask application object.
:param config_filename: absolute or relative filename of the config file
:param instance_path: instance path to initialize or run a VeriPress app
:return: a Flask app object
"""
app_ = CustomFlask(
__name__,
instance_path=instance_path or os.environ.get(
'VERIPRESS_INSTANCE_PATH') or os.getcwd(),
instance_relative_config=True
)
app_.config.update(dict(STORAGE_TYPE='file',
THEME='default',
CACHE_TYPE='simple',
MODE='view-only',
ENTRIES_PER_PAGE=5,
FEED_COUNT=10,
SHOW_TOC=True,
TOC_DEPTH=3,
TOC_LOWEST_LEVEL=3,
ALLOW_SEARCH_PAGES=True,
PAGE_SOURCE_ACCESSIBLE=False))
app_.config.from_pyfile(config_filename, silent=True)
theme_folder = os.path.join(app_.instance_path,
'themes', app_.config['THEME'])
# use templates in the selected theme's folder
app_.template_folder = os.path.join(theme_folder, 'templates')
# use static files in the selected theme's folder
app_.theme_static_folder = os.path.join(theme_folder, 'static')
# global static folder
app_.static_folder = os.path.join(app_.instance_path, 'static')
return app_ | python | def create_app(config_filename, instance_path=None):
"""
Factory function to create Flask application object.
:param config_filename: absolute or relative filename of the config file
:param instance_path: instance path to initialize or run a VeriPress app
:return: a Flask app object
"""
app_ = CustomFlask(
__name__,
instance_path=instance_path or os.environ.get(
'VERIPRESS_INSTANCE_PATH') or os.getcwd(),
instance_relative_config=True
)
app_.config.update(dict(STORAGE_TYPE='file',
THEME='default',
CACHE_TYPE='simple',
MODE='view-only',
ENTRIES_PER_PAGE=5,
FEED_COUNT=10,
SHOW_TOC=True,
TOC_DEPTH=3,
TOC_LOWEST_LEVEL=3,
ALLOW_SEARCH_PAGES=True,
PAGE_SOURCE_ACCESSIBLE=False))
app_.config.from_pyfile(config_filename, silent=True)
theme_folder = os.path.join(app_.instance_path,
'themes', app_.config['THEME'])
# use templates in the selected theme's folder
app_.template_folder = os.path.join(theme_folder, 'templates')
# use static files in the selected theme's folder
app_.theme_static_folder = os.path.join(theme_folder, 'static')
# global static folder
app_.static_folder = os.path.join(app_.instance_path, 'static')
return app_ | Factory function to create Flask application object.
:param config_filename: absolute or relative filename of the config file
:param instance_path: instance path to initialize or run a VeriPress app
:return: a Flask app object | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/__init__.py#L30-L66 |
veripress/veripress | veripress/__init__.py | CustomFlask.send_static_file | def send_static_file(self, filename):
"""
Send static files from the static folder
in the current selected theme prior to the global static folder.
:param filename: static filename
:return: response object
"""
if self.config['MODE'] == 'api-only':
# if 'api-only' mode is set, we should not send static files
abort(404)
theme_static_folder = getattr(self, 'theme_static_folder', None)
if theme_static_folder:
try:
return send_from_directory(theme_static_folder, filename)
except NotFound:
pass
return super(CustomFlask, self).send_static_file(filename) | python | def send_static_file(self, filename):
"""
Send static files from the static folder
in the current selected theme prior to the global static folder.
:param filename: static filename
:return: response object
"""
if self.config['MODE'] == 'api-only':
# if 'api-only' mode is set, we should not send static files
abort(404)
theme_static_folder = getattr(self, 'theme_static_folder', None)
if theme_static_folder:
try:
return send_from_directory(theme_static_folder, filename)
except NotFound:
pass
return super(CustomFlask, self).send_static_file(filename) | Send static files from the static folder
in the current selected theme prior to the global static folder.
:param filename: static filename
:return: response object | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/__init__.py#L9-L27 |
elsampsa/valkka-live | valkka/live/container/video.py | VideoContainer.setDevice | def setDevice(self, device):
"""Sets the video stream
:param device: A rather generic device class. In this case DataModel.RTSPCameraDevice.
"""
print(self.pre, "setDevice :", device)
if (not device and not self.device): # None can be passed as an argument when the device has not been set yet
return
if (self.device):
if self.device == device:
print(self.pre, "setDevice : same device")
return
if self.filterchain: # there's video already
self.clearDevice()
self.device = device
self.video.setDevice(self.device) # inform the video widget so it can start drags
# ManagedFilterChain.addViewPort accepts ViewPort instance
self.filterchain = self.filterchain_group.get(_id = self.device._id)
if self.filterchain:
self.viewport.setXScreenNum(self.n_xscreen)
self.viewport.setWindowId (int(self.video.winId()))
self.filterchain.addViewPort(self.viewport) | python | def setDevice(self, device):
"""Sets the video stream
:param device: A rather generic device class. In this case DataModel.RTSPCameraDevice.
"""
print(self.pre, "setDevice :", device)
if (not device and not self.device): # None can be passed as an argument when the device has not been set yet
return
if (self.device):
if self.device == device:
print(self.pre, "setDevice : same device")
return
if self.filterchain: # there's video already
self.clearDevice()
self.device = device
self.video.setDevice(self.device) # inform the video widget so it can start drags
# ManagedFilterChain.addViewPort accepts ViewPort instance
self.filterchain = self.filterchain_group.get(_id = self.device._id)
if self.filterchain:
self.viewport.setXScreenNum(self.n_xscreen)
self.viewport.setWindowId (int(self.video.winId()))
self.filterchain.addViewPort(self.viewport) | Sets the video stream
:param device: A rather generic device class. In this case DataModel.RTSPCameraDevice. | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/video.py#L234-L261 |
elsampsa/valkka-live | valkka/live/container/video.py | VideoContainer.clearDevice | def clearDevice(self):
"""Remove the current stream
"""
print(self.pre, "clearDevice")
if not self.device:
return
self.filterchain.delViewPort(self.viewport)
self.filterchain = None
self.device = None
self.video.update() | python | def clearDevice(self):
"""Remove the current stream
"""
print(self.pre, "clearDevice")
if not self.device:
return
self.filterchain.delViewPort(self.viewport)
self.filterchain = None
self.device = None
self.video.update() | Remove the current stream | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/video.py#L264-L276 |
elsampsa/valkka-live | valkka/live/container/video.py | VideoContainer.mouseGestureHandler | def mouseGestureHandler(self, info):
"""This is the callback for MouseClickContext. Passed to VideoWidget as a parameter
"""
print(self.pre, ": mouseGestureHandler: ")
# *** single click events ***
if (info.fsingle):
print(self.pre, ": mouseGestureHandler: single click")
if (info.button == QtCore.Qt.LeftButton):
print(self.pre, ": mouseGestureHandler: Left button clicked")
elif (info.button == QtCore.Qt.RightButton):
print(self.pre, ": mouseGestureHandler: Right button clicked")
self.handle_right_single_click(info)
# *** double click events ***
elif (info.fdouble):
if (info.button == QtCore.Qt.LeftButton):
print(
self.pre,
": mouseGestureHandler: Left button double-clicked")
self.handle_left_double_click(info)
elif (info.button == QtCore.Qt.RightButton):
print(
self.pre,
": mouseGestureHandler: Right button double-clicked") | python | def mouseGestureHandler(self, info):
"""This is the callback for MouseClickContext. Passed to VideoWidget as a parameter
"""
print(self.pre, ": mouseGestureHandler: ")
# *** single click events ***
if (info.fsingle):
print(self.pre, ": mouseGestureHandler: single click")
if (info.button == QtCore.Qt.LeftButton):
print(self.pre, ": mouseGestureHandler: Left button clicked")
elif (info.button == QtCore.Qt.RightButton):
print(self.pre, ": mouseGestureHandler: Right button clicked")
self.handle_right_single_click(info)
# *** double click events ***
elif (info.fdouble):
if (info.button == QtCore.Qt.LeftButton):
print(
self.pre,
": mouseGestureHandler: Left button double-clicked")
self.handle_left_double_click(info)
elif (info.button == QtCore.Qt.RightButton):
print(
self.pre,
": mouseGestureHandler: Right button double-clicked") | This is the callback for MouseClickContext. Passed to VideoWidget as a parameter | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/video.py#L283-L305 |
elsampsa/valkka-live | valkka/live/container/video.py | VideoContainer.handle_left_double_click | def handle_left_double_click(self, info):
"""Whatever we want to do, when the VideoWidget has been double-clicked with the left button
"""
if (self.double_click_focus == False): # turn focus on
print(self.pre, "handle_left_double_click: focus on")
self.cb_focus()
else: # turn focus off
print(self.pre, "handle_left_double_click: focus off")
self.cb_unfocus()
self.double_click_focus = not(
self.double_click_focus) | python | def handle_left_double_click(self, info):
"""Whatever we want to do, when the VideoWidget has been double-clicked with the left button
"""
if (self.double_click_focus == False): # turn focus on
print(self.pre, "handle_left_double_click: focus on")
self.cb_focus()
else: # turn focus off
print(self.pre, "handle_left_double_click: focus off")
self.cb_unfocus()
self.double_click_focus = not(
self.double_click_focus) | Whatever we want to do, when the VideoWidget has been double-clicked with the left button | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/video.py#L309-L319 |
veripress/veripress | veripress/model/__init__.py | get_storage | def get_storage():
"""
Get storage object of current app context,
will create a new one if not exists.
:return: a storage object
:raise: ConfigurationError: storage type in config is not supported
"""
storage_ = getattr(g, '_storage', None)
if storage_ is None:
storage_type = current_app.config['STORAGE_TYPE']
if storage_type == 'file':
storage_ = g._storage = storages.FileStorage()
else:
raise ConfigurationError(
'Storage type "{}" is not supported.'.format(storage_type))
return storage_ | python | def get_storage():
"""
Get storage object of current app context,
will create a new one if not exists.
:return: a storage object
:raise: ConfigurationError: storage type in config is not supported
"""
storage_ = getattr(g, '_storage', None)
if storage_ is None:
storage_type = current_app.config['STORAGE_TYPE']
if storage_type == 'file':
storage_ = g._storage = storages.FileStorage()
else:
raise ConfigurationError(
'Storage type "{}" is not supported.'.format(storage_type))
return storage_ | Get storage object of current app context,
will create a new one if not exists.
:return: a storage object
:raise: ConfigurationError: storage type in config is not supported | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/__init__.py#L11-L27 |
elsampsa/valkka-live | valkka/live/form.py | SlotFormSet.chooseForm_slot | def chooseForm_slot(self, element, element_old):
"""Calling this slot chooses the form to be shown
:param element: an object that has *_id* and *classname* attributes
:param element_old: an object that has *_id* and *classname* attributes
This slot is typically connected to List classes, widget attribute's, currentItemChanged method (List.widget is QListWidget that has currentItemChanged slot), so the element and element_old parameters are QListWidgetItem instances with extra attributes "_id" and "_classname" attached.
Queries the database for element._id
"""
self.current_slot = None
if (verbose):
# enable this if you're unsure what's coming here..
print(self.pre, "chooseForm_slot :", element)
if (isinstance(element, type(None))):
self.current_row = None
self.element = None
else:
# print(self.pre,"chooseForm_slot :",element)
assert(hasattr(element, "_id"))
assert(hasattr(element, "classname"))
try:
self.current_row = self.row_instance_by_name[element.classname]
except KeyError:
print(
self.pre,
"chooseForm_slot : no such classname for this FormSet : ",
element.classname)
self.current_row = None
self.element = None
else:
self.resetForm()
self.current_row.get(self.collection, element._id)
self.element = element
self.current_slot = self.current_row.get_column_value("slot")
self.showCurrent() | python | def chooseForm_slot(self, element, element_old):
"""Calling this slot chooses the form to be shown
:param element: an object that has *_id* and *classname* attributes
:param element_old: an object that has *_id* and *classname* attributes
This slot is typically connected to List classes, widget attribute's, currentItemChanged method (List.widget is QListWidget that has currentItemChanged slot), so the element and element_old parameters are QListWidgetItem instances with extra attributes "_id" and "_classname" attached.
Queries the database for element._id
"""
self.current_slot = None
if (verbose):
# enable this if you're unsure what's coming here..
print(self.pre, "chooseForm_slot :", element)
if (isinstance(element, type(None))):
self.current_row = None
self.element = None
else:
# print(self.pre,"chooseForm_slot :",element)
assert(hasattr(element, "_id"))
assert(hasattr(element, "classname"))
try:
self.current_row = self.row_instance_by_name[element.classname]
except KeyError:
print(
self.pre,
"chooseForm_slot : no such classname for this FormSet : ",
element.classname)
self.current_row = None
self.element = None
else:
self.resetForm()
self.current_row.get(self.collection, element._id)
self.element = element
self.current_slot = self.current_row.get_column_value("slot")
self.showCurrent() | Calling this slot chooses the form to be shown
:param element: an object that has *_id* and *classname* attributes
:param element_old: an object that has *_id* and *classname* attributes
This slot is typically connected to List classes, widget attribute's, currentItemChanged method (List.widget is QListWidget that has currentItemChanged slot), so the element and element_old parameters are QListWidgetItem instances with extra attributes "_id" and "_classname" attached.
Queries the database for element._id | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/form.py#L74-L112 |
elsampsa/valkka-live | valkka/live/form.py | SlotFormSet.update_dropdown_list_slot | def update_dropdown_list_slot(self):
"""Keep updating the dropdown list. Say, don't let the user choose USB devices if none is available
"""
self.dropdown_widget.clear() # this will trigger dropdown_changed_slot
self.row_instance_by_index = []
for i, key in enumerate(self.row_instance_by_name.keys()):
row_instance = self.row_instance_by_name[key]
if (row_instance.isActive()):
self.row_instance_by_index.append(row_instance)
display_name = row_instance.getName()
self.dropdown_widget.insertItem(i, display_name)
row_instance.updateWidget() | python | def update_dropdown_list_slot(self):
"""Keep updating the dropdown list. Say, don't let the user choose USB devices if none is available
"""
self.dropdown_widget.clear() # this will trigger dropdown_changed_slot
self.row_instance_by_index = []
for i, key in enumerate(self.row_instance_by_name.keys()):
row_instance = self.row_instance_by_name[key]
if (row_instance.isActive()):
self.row_instance_by_index.append(row_instance)
display_name = row_instance.getName()
self.dropdown_widget.insertItem(i, display_name)
row_instance.updateWidget() | Keep updating the dropdown list. Say, don't let the user choose USB devices if none is available | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/form.py#L190-L201 |
elsampsa/valkka-live | valkka/live/filterchain.py | FilterChainGroup.read | def read(self):
"""Reads all devices from the database and creates filterchains
TODO: we can, of course, just modify the added / removed cameras
"""
self.reset()
for dic in self.datamodel.camera_collection.get(): # TODO: search directly for RTSPCameraRow
if (self.verbose): print(self.pre, "read : dic", dic)
if (dic["classname"] == DataModel.RTSPCameraRow.__name__):
affinity = -1
if self.cpu_scheme:
affinity = self.cpu_scheme.getAV()
dic.pop("classname")
device = DataModel.RTSPCameraDevice(**dic) # a neat object with useful methods
print("FilterChainGroup : read : slot =", device.getLiveMainSlot())
print("FilterChainGroup : read : address =", device.getMainAddress())
print("FilterChainGroup : read : _id =", device._id)
# chain = ManagedFilterchain( # decoding and branching the stream happens here
# chain = ManagedFilterchain2( # decoding and branching the stream happens here
chain = LiveManagedFilterchain( # decoding and branching the stream happens here
livethread = self.livethread,
openglthreads
= self.gpu_handler.openglthreads,
address = device.getMainAddress(),
slot = device.getLiveMainSlot(),
_id = device._id,
affinity = affinity,
msreconnect = 10000,
# verbose = True,
verbose =False,
shmem_image_dimensions = constant.shmem_image_dimensions,
shmem_n_buffer = constant.shmem_n_buffer,
shmem_image_interval = constant.shmem_image_interval
)
self.chains.append(chain) # important .. otherwise chain will go out of context and get garbage collected
elif (dic["classname"] == DataModel.USBCameraRow.__name__):
affinity = -1
if self.cpu_scheme:
affinity = self.cpu_scheme.getAV()
dic.pop("classname")
device = DataModel.USBCameraDevice(**dic) # a neat object with useful methods
print("FilterChainGroup : read : slot =", device.getLiveMainSlot())
print("FilterChainGroup : read : address =", device.getMainAddress())
print("FilterChainGroup : read : _id =", device._id)
chain = USBManagedFilterchain( # decoding and branching the stream happens here
usbthread = self.usbthread,
openglthreads
= self.gpu_handler.openglthreads,
address = device.getMainAddress(),
slot = device.getLiveMainSlot(),
_id = device._id,
affinity = affinity,
msreconnect = 10000,
# verbose = True,
verbose =False,
shmem_image_dimensions = constant.shmem_image_dimensions,
shmem_n_buffer = constant.shmem_n_buffer,
shmem_image_interval = constant.shmem_image_interval
)
self.chains.append(chain) | python | def read(self):
"""Reads all devices from the database and creates filterchains
TODO: we can, of course, just modify the added / removed cameras
"""
self.reset()
for dic in self.datamodel.camera_collection.get(): # TODO: search directly for RTSPCameraRow
if (self.verbose): print(self.pre, "read : dic", dic)
if (dic["classname"] == DataModel.RTSPCameraRow.__name__):
affinity = -1
if self.cpu_scheme:
affinity = self.cpu_scheme.getAV()
dic.pop("classname")
device = DataModel.RTSPCameraDevice(**dic) # a neat object with useful methods
print("FilterChainGroup : read : slot =", device.getLiveMainSlot())
print("FilterChainGroup : read : address =", device.getMainAddress())
print("FilterChainGroup : read : _id =", device._id)
# chain = ManagedFilterchain( # decoding and branching the stream happens here
# chain = ManagedFilterchain2( # decoding and branching the stream happens here
chain = LiveManagedFilterchain( # decoding and branching the stream happens here
livethread = self.livethread,
openglthreads
= self.gpu_handler.openglthreads,
address = device.getMainAddress(),
slot = device.getLiveMainSlot(),
_id = device._id,
affinity = affinity,
msreconnect = 10000,
# verbose = True,
verbose =False,
shmem_image_dimensions = constant.shmem_image_dimensions,
shmem_n_buffer = constant.shmem_n_buffer,
shmem_image_interval = constant.shmem_image_interval
)
self.chains.append(chain) # important .. otherwise chain will go out of context and get garbage collected
elif (dic["classname"] == DataModel.USBCameraRow.__name__):
affinity = -1
if self.cpu_scheme:
affinity = self.cpu_scheme.getAV()
dic.pop("classname")
device = DataModel.USBCameraDevice(**dic) # a neat object with useful methods
print("FilterChainGroup : read : slot =", device.getLiveMainSlot())
print("FilterChainGroup : read : address =", device.getMainAddress())
print("FilterChainGroup : read : _id =", device._id)
chain = USBManagedFilterchain( # decoding and branching the stream happens here
usbthread = self.usbthread,
openglthreads
= self.gpu_handler.openglthreads,
address = device.getMainAddress(),
slot = device.getLiveMainSlot(),
_id = device._id,
affinity = affinity,
msreconnect = 10000,
# verbose = True,
verbose =False,
shmem_image_dimensions = constant.shmem_image_dimensions,
shmem_n_buffer = constant.shmem_n_buffer,
shmem_image_interval = constant.shmem_image_interval
)
self.chains.append(chain) | Reads all devices from the database and creates filterchains
TODO: we can, of course, just modify the added / removed cameras | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/filterchain.py#L74-L143 |
elsampsa/valkka-live | valkka/live/filterchain.py | FilterChainGroup.update | def update(self):
"""Reads all devices from the database. Creates new filterchains and removes old ones
TODO: currently this is broken: if user changes any other field than the ip address, the cameras don't get updated
"""
raise(AssertionError("out of date"))
new_ids = []
old_ids = []
# collect old ip addresses
for chain in self.chains:
if (self.verbose): print(self.pre, "old :", chain, chain.get__id(), chain.get_address(), chain._id)
old_ids.append(chain.get__id())
# collect devices
devices = []
for dic in self.datamodel.camera_collection.get():
if (self.verbose): print(self.pre, "update : dic", dic)
if (dic["classname"] == DataModel.RTSPCameraRow.__name__):
devices.append(dic)
devices_by_id={}
for dic in devices: # DataModel.RTSPCameraRow instances
_id = dic["_id"]
new_ids.append(_id)
devices_by_id[_id] = dic
if (self.verbose):
print(self.pre, "update : new_ids =", new_ids)
print(self.pre, "update : old_ids =", old_ids)
add_list = list(set(new_ids).difference(set(old_ids))) # cams to be added
rem_list = list(set(old_ids).difference(set(new_ids))) # cams to be removed
if (self.verbose):
print(self.pre, "update : add_list =", add_list)
print(self.pre, "update : rem_list =", rem_list)
# purge removed chains
for i, chain in enumerate(self.chains):
if (chain.get__id() in rem_list):
chain_ = self.chains.pop(i)
if (self.verbose): print(self.pre, "closing chain", chain_)
chain_.close()
# add new chains
for new_address in add_list:
dic = devices_by_id[new_address]
chain = ManagedFilterchain( # decoding and branching the stream happens here
livethread = self.livethread,
openglthreads
= self.gpu_handler.openglthreads,
address = DataModel.RTSPCameraRow.getMainAddressFromDict(dic),
slot = dic["slot"],
_id = dic["_id"],
# affinity = a,
msreconnect = 10000,
verbose = True
)
if (self.verbose): print(self.pre, "adding chain", chain)
self.chains.append(chain) | python | def update(self):
"""Reads all devices from the database. Creates new filterchains and removes old ones
TODO: currently this is broken: if user changes any other field than the ip address, the cameras don't get updated
"""
raise(AssertionError("out of date"))
new_ids = []
old_ids = []
# collect old ip addresses
for chain in self.chains:
if (self.verbose): print(self.pre, "old :", chain, chain.get__id(), chain.get_address(), chain._id)
old_ids.append(chain.get__id())
# collect devices
devices = []
for dic in self.datamodel.camera_collection.get():
if (self.verbose): print(self.pre, "update : dic", dic)
if (dic["classname"] == DataModel.RTSPCameraRow.__name__):
devices.append(dic)
devices_by_id={}
for dic in devices: # DataModel.RTSPCameraRow instances
_id = dic["_id"]
new_ids.append(_id)
devices_by_id[_id] = dic
if (self.verbose):
print(self.pre, "update : new_ids =", new_ids)
print(self.pre, "update : old_ids =", old_ids)
add_list = list(set(new_ids).difference(set(old_ids))) # cams to be added
rem_list = list(set(old_ids).difference(set(new_ids))) # cams to be removed
if (self.verbose):
print(self.pre, "update : add_list =", add_list)
print(self.pre, "update : rem_list =", rem_list)
# purge removed chains
for i, chain in enumerate(self.chains):
if (chain.get__id() in rem_list):
chain_ = self.chains.pop(i)
if (self.verbose): print(self.pre, "closing chain", chain_)
chain_.close()
# add new chains
for new_address in add_list:
dic = devices_by_id[new_address]
chain = ManagedFilterchain( # decoding and branching the stream happens here
livethread = self.livethread,
openglthreads
= self.gpu_handler.openglthreads,
address = DataModel.RTSPCameraRow.getMainAddressFromDict(dic),
slot = dic["slot"],
_id = dic["_id"],
# affinity = a,
msreconnect = 10000,
verbose = True
)
if (self.verbose): print(self.pre, "adding chain", chain)
self.chains.append(chain) | Reads all devices from the database. Creates new filterchains and removes old ones
TODO: currently this is broken: if user changes any other field than the ip address, the cameras don't get updated | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/filterchain.py#L148-L209 |
elsampsa/valkka-live | valkka/live/filterchain.py | FilterChainGroup.get | def get(self, **kwargs):
"""Find correct filterchain based on generic variables
"""
for chain in self.chains:
for key in kwargs:
getter_name = "get_"+key
# scan all possible getters
if (hasattr(chain, getter_name)):
getter = getattr(chain, getter_name) # e.g. "get_address"
if (getter() == kwargs[key]):
return chain
return None | python | def get(self, **kwargs):
"""Find correct filterchain based on generic variables
"""
for chain in self.chains:
for key in kwargs:
getter_name = "get_"+key
# scan all possible getters
if (hasattr(chain, getter_name)):
getter = getattr(chain, getter_name) # e.g. "get_address"
if (getter() == kwargs[key]):
return chain
return None | Find correct filterchain based on generic variables | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/filterchain.py#L214-L225 |
elsampsa/valkka-live | valkka/live/filterchain.py | FilterChainGroup.getDevice | def getDevice(self, **kwargs):
"""Like get, but returns a Device instance (RTSPCameraDevice, etc.)
"""
filterchain = self.get(**kwargs)
if not filterchain:
return None
# get filterchain init parameters that are compatible with RTSPCameraDevice input parameters
pars = filterchain.getParDic(DataModel.RTSPCameraDevice.parameter_defs)
# .. and instantiate an RTSPCameraDevice with those parameters
device = DataModel.RTSPCameraDevice(**pars)
print(self.pre, "getDevice :", pars, device)
return device | python | def getDevice(self, **kwargs):
"""Like get, but returns a Device instance (RTSPCameraDevice, etc.)
"""
filterchain = self.get(**kwargs)
if not filterchain:
return None
# get filterchain init parameters that are compatible with RTSPCameraDevice input parameters
pars = filterchain.getParDic(DataModel.RTSPCameraDevice.parameter_defs)
# .. and instantiate an RTSPCameraDevice with those parameters
device = DataModel.RTSPCameraDevice(**pars)
print(self.pre, "getDevice :", pars, device)
return device | Like get, but returns a Device instance (RTSPCameraDevice, etc.) | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/filterchain.py#L229-L244 |
veripress/veripress | veripress/model/models.py | Base.to_dict | def to_dict(self):
"""
Convert attributes and properties to a dict,
so that it can be serialized.
"""
return {k: getattr(self, k) for k in filter(
lambda k: not k.startswith('_') and k != 'to_dict', dir(self))} | python | def to_dict(self):
"""
Convert attributes and properties to a dict,
so that it can be serialized.
"""
return {k: getattr(self, k) for k in filter(
lambda k: not k.startswith('_') and k != 'to_dict', dir(self))} | Convert attributes and properties to a dict,
so that it can be serialized. | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/models.py#L30-L36 |
veripress/veripress | veripress/model/toc.py | _HtmlHeaderNode.to_dict | def to_dict(self):
"""Convert self to a dict object for serialization."""
return {
'level': self.level,
'id': self.id,
'text': self.text,
'inner_html': self.inner_html,
'children': [child.to_dict() for child in self.children]
} | python | def to_dict(self):
"""Convert self to a dict object for serialization."""
return {
'level': self.level,
'id': self.id,
'text': self.text,
'inner_html': self.inner_html,
'children': [child.to_dict() for child in self.children]
} | Convert self to a dict object for serialization. | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/toc.py#L24-L32 |
veripress/veripress | veripress/model/toc.py | HtmlTocParser.toc | def toc(self, depth=6, lowest_level=6):
"""
Get table of content of currently fed HTML string.
:param depth: the depth of TOC
:param lowest_level: the allowed lowest level of header tag
:return: a list representing the TOC
"""
depth = min(max(depth, 0), 6)
depth = 6 if depth == 0 else depth
lowest_level = min(max(lowest_level, 1), 6)
toc = self._root.to_dict()['children']
def traverse(curr_toc, dep, lowest_lvl, curr_depth=1):
if curr_depth > dep:
# clear all items of this depth and exit the recursion
curr_toc.clear()
return
items_to_remove = []
for item in curr_toc:
if item['level'] > lowest_lvl:
# record item with low header level, for removing it later
items_to_remove.append(item)
else:
traverse(item['children'], dep, lowest_lvl, curr_depth + 1)
[curr_toc.remove(item) for item in items_to_remove]
traverse(toc, depth, lowest_level)
return toc | python | def toc(self, depth=6, lowest_level=6):
"""
Get table of content of currently fed HTML string.
:param depth: the depth of TOC
:param lowest_level: the allowed lowest level of header tag
:return: a list representing the TOC
"""
depth = min(max(depth, 0), 6)
depth = 6 if depth == 0 else depth
lowest_level = min(max(lowest_level, 1), 6)
toc = self._root.to_dict()['children']
def traverse(curr_toc, dep, lowest_lvl, curr_depth=1):
if curr_depth > dep:
# clear all items of this depth and exit the recursion
curr_toc.clear()
return
items_to_remove = []
for item in curr_toc:
if item['level'] > lowest_lvl:
# record item with low header level, for removing it later
items_to_remove.append(item)
else:
traverse(item['children'], dep, lowest_lvl, curr_depth + 1)
[curr_toc.remove(item) for item in items_to_remove]
traverse(toc, depth, lowest_level)
return toc | Get table of content of currently fed HTML string.
:param depth: the depth of TOC
:param lowest_level: the allowed lowest level of header tag
:return: a list representing the TOC | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/toc.py#L61-L90 |
veripress/veripress | veripress/model/toc.py | HtmlTocParser.toc_html | def toc_html(self, depth=6, lowest_level=6):
"""
Get TOC of currently fed HTML string in form of HTML string.
:param depth: the depth of TOC
:param lowest_level: the allowed lowest level of header tag
:return: an HTML string
"""
toc = self.toc(depth=depth, lowest_level=lowest_level)
if not toc:
return ''
def map_toc_list(toc_list):
result = ''
if toc_list:
result += '<ul>\n'
result += ''.join(
map(lambda x: '<li>'
'<a href="#{}">{}</a>{}'
'</li>\n'.format(
x['id'], x['inner_html'],
map_toc_list(x['children'])),
toc_list)
)
result += '</ul>'
return result
return map_toc_list(toc) | python | def toc_html(self, depth=6, lowest_level=6):
"""
Get TOC of currently fed HTML string in form of HTML string.
:param depth: the depth of TOC
:param lowest_level: the allowed lowest level of header tag
:return: an HTML string
"""
toc = self.toc(depth=depth, lowest_level=lowest_level)
if not toc:
return ''
def map_toc_list(toc_list):
result = ''
if toc_list:
result += '<ul>\n'
result += ''.join(
map(lambda x: '<li>'
'<a href="#{}">{}</a>{}'
'</li>\n'.format(
x['id'], x['inner_html'],
map_toc_list(x['children'])),
toc_list)
)
result += '</ul>'
return result
return map_toc_list(toc) | Get TOC of currently fed HTML string in form of HTML string.
:param depth: the depth of TOC
:param lowest_level: the allowed lowest level of header tag
:return: an HTML string | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/toc.py#L92-L119 |
veripress/veripress | veripress/model/toc.py | HtmlTocParser._get_level | def _get_level(tag):
"""
Match the header level in the given tag name,
or None if it's not a header tag.
"""
m = re.match(r'^h([123456])$', tag, flags=re.IGNORECASE)
if not m:
return None
return int(m.group(1)) | python | def _get_level(tag):
"""
Match the header level in the given tag name,
or None if it's not a header tag.
"""
m = re.match(r'^h([123456])$', tag, flags=re.IGNORECASE)
if not m:
return None
return int(m.group(1)) | Match the header level in the given tag name,
or None if it's not a header tag. | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/model/toc.py#L136-L144 |
elsampsa/valkka-live | valkka/mvision/yolo3/base.py | MVisionProcess.requiredGPU_MB | def requiredGPU_MB(self, n):
"""Required GPU memory in MBytes
"""
from darknet.core import darknet_with_cuda
if (darknet_with_cuda()): # its using cuda
free = getFreeGPU_MB()
print("Yolo: requiredGPU_MB: required, free", n, free)
if (free == -1): # could not detect ..
return True
return (free>=n)
else:
return True | python | def requiredGPU_MB(self, n):
"""Required GPU memory in MBytes
"""
from darknet.core import darknet_with_cuda
if (darknet_with_cuda()): # its using cuda
free = getFreeGPU_MB()
print("Yolo: requiredGPU_MB: required, free", n, free)
if (free == -1): # could not detect ..
return True
return (free>=n)
else:
return True | Required GPU memory in MBytes | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/yolo3/base.py#L149-L160 |
elsampsa/valkka-live | valkka/mvision/yolo3/base.py | MVisionProcess.postActivate_ | def postActivate_(self):
"""Whatever you need to do after creating the shmem client
"""
if (self.requiredGPU_MB(self.required_mb)):
self.analyzer = YoloV3Analyzer(verbose = self.verbose)
else:
self.warning_message = "WARNING: not enough GPU memory!"
self.analyzer = None | python | def postActivate_(self):
"""Whatever you need to do after creating the shmem client
"""
if (self.requiredGPU_MB(self.required_mb)):
self.analyzer = YoloV3Analyzer(verbose = self.verbose)
else:
self.warning_message = "WARNING: not enough GPU memory!"
self.analyzer = None | Whatever you need to do after creating the shmem client | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/yolo3/base.py#L162-L169 |
elsampsa/valkka-live | valkka/mvision/yolo3/base.py | MVisionProcess.getWidget | def getWidget(self):
"""Some ideas for your widget:
- Textual information (alert, license place number)
- Check boxes : if checked, send e-mail to your mom when the analyzer spots something
- .. or send an sms to yourself
- You can include the cv2.imshow window to the widget to see how the analyzer proceeds
"""
self.widget = QtWidgets.QTextEdit()
self.widget.setStyleSheet(style.detector_test)
self.widget.setReadOnly(True)
self.signals.objects.connect(self.objects_slot)
return self.widget | python | def getWidget(self):
"""Some ideas for your widget:
- Textual information (alert, license place number)
- Check boxes : if checked, send e-mail to your mom when the analyzer spots something
- .. or send an sms to yourself
- You can include the cv2.imshow window to the widget to see how the analyzer proceeds
"""
self.widget = QtWidgets.QTextEdit()
self.widget.setStyleSheet(style.detector_test)
self.widget.setReadOnly(True)
self.signals.objects.connect(self.objects_slot)
return self.widget | Some ideas for your widget:
- Textual information (alert, license place number)
- Check boxes : if checked, send e-mail to your mom when the analyzer spots something
- .. or send an sms to yourself
- You can include the cv2.imshow window to the widget to see how the analyzer proceeds | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/yolo3/base.py#L249-L260 |
Jaymon/pout | pout/value.py | Inspect.typename | def typename(self):
'''
get the type of val
there are multiple places where we want to know if val is an object, or a string, or whatever,
this method allows us to find out that information
since -- 7-10-12
val -- mixed -- the value to check
return -- string -- the type
'''
t = 'DEFAULT'
# http://docs.python.org/2/library/types.html
# func_types = (
# types.FunctionType,
# types.BuiltinFunctionType,
# types.MethodType,
# types.UnboundMethodType,
# types.BuiltinFunctionType,
# types.BuiltinMethodType,
# classmethod
# )
if self.is_primitive():
t = 'DEFAULT'
elif self.is_dict():
t = 'DICT'
elif self.is_list():
t = 'LIST'
elif self.is_array():
t = 'ARRAY'
elif self.is_tuple():
t = 'TUPLE'
elif self.is_type():
t = 'TYPE'
elif self.is_binary():
t = 'BINARY'
elif self.is_str():
t = 'STRING'
elif self.is_exception():
t = 'EXCEPTION'
elif self.is_module():
# this has to go before the object check since a module will pass the object tests
t = 'MODULE'
elif self.is_callable():
t = 'FUNCTION'
# not doing this one since it can cause the class instance to do unexpected
# things just to print it out
#elif isinstance(val, property):
# uses the @property decorator and the like
#t = 'PROPERTY'
elif self.is_dict_proxy():
# maybe we have a dict proxy?
t = 'DICT_PROXY'
elif self.is_generator():
t = 'GENERATOR'
elif self.is_set():
t = 'SET'
elif self.is_object():
t = 'OBJECT'
# elif isinstance(val, func_types) and hasattr(val, '__call__'):
# # this has to go after object because lots of times objects can be classified as functions
# # http://stackoverflow.com/questions/624926/
# t = 'FUNCTION'
elif self.is_regex():
t = 'REGEX'
else:
t = 'DEFAULT'
return t | python | def typename(self):
'''
get the type of val
there are multiple places where we want to know if val is an object, or a string, or whatever,
this method allows us to find out that information
since -- 7-10-12
val -- mixed -- the value to check
return -- string -- the type
'''
t = 'DEFAULT'
# http://docs.python.org/2/library/types.html
# func_types = (
# types.FunctionType,
# types.BuiltinFunctionType,
# types.MethodType,
# types.UnboundMethodType,
# types.BuiltinFunctionType,
# types.BuiltinMethodType,
# classmethod
# )
if self.is_primitive():
t = 'DEFAULT'
elif self.is_dict():
t = 'DICT'
elif self.is_list():
t = 'LIST'
elif self.is_array():
t = 'ARRAY'
elif self.is_tuple():
t = 'TUPLE'
elif self.is_type():
t = 'TYPE'
elif self.is_binary():
t = 'BINARY'
elif self.is_str():
t = 'STRING'
elif self.is_exception():
t = 'EXCEPTION'
elif self.is_module():
# this has to go before the object check since a module will pass the object tests
t = 'MODULE'
elif self.is_callable():
t = 'FUNCTION'
# not doing this one since it can cause the class instance to do unexpected
# things just to print it out
#elif isinstance(val, property):
# uses the @property decorator and the like
#t = 'PROPERTY'
elif self.is_dict_proxy():
# maybe we have a dict proxy?
t = 'DICT_PROXY'
elif self.is_generator():
t = 'GENERATOR'
elif self.is_set():
t = 'SET'
elif self.is_object():
t = 'OBJECT'
# elif isinstance(val, func_types) and hasattr(val, '__call__'):
# # this has to go after object because lots of times objects can be classified as functions
# # http://stackoverflow.com/questions/624926/
# t = 'FUNCTION'
elif self.is_regex():
t = 'REGEX'
else:
t = 'DEFAULT'
return t | get the type of val
there are multiple places where we want to know if val is an object, or a string, or whatever,
this method allows us to find out that information
since -- 7-10-12
val -- mixed -- the value to check
return -- string -- the type | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/value.py#L41-L130 |
Jaymon/pout | pout/value.py | Inspect.is_primitive | def is_primitive(self):
"""is the value a built-in type?"""
if is_py2:
return isinstance(
self.val,
(
types.NoneType,
types.BooleanType,
types.IntType,
types.LongType,
types.FloatType
)
)
else:
return isinstance(
self.val,
(
type(None),
bool,
int,
float
)
) | python | def is_primitive(self):
"""is the value a built-in type?"""
if is_py2:
return isinstance(
self.val,
(
types.NoneType,
types.BooleanType,
types.IntType,
types.LongType,
types.FloatType
)
)
else:
return isinstance(
self.val,
(
type(None),
bool,
int,
float
)
) | is the value a built-in type? | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/value.py#L145-L168 |
Jaymon/pout | pout/value.py | Value._str_iterator | def _str_iterator(self, iterator, name_callback=None, prefix="\n", left_paren='[', right_paren=']', depth=0):
'''
turn an iteratable value into a string representation
iterator -- iterator -- the value to be iterated through
name_callback -- callback -- if not None, a function that will take the key of each iteration
prefix -- string -- what will be prepended to the generated value
left_paren -- string -- what will open the generated value
right_paren -- string -- what will close the generated value
depth -- integer -- how deep into recursion we are
return -- string
'''
indent = 1 if depth > 0 else 0
s = []
s.append('{}{}'.format(prefix, self._add_indent(left_paren, indent)))
s_body = []
for k, v in iterator:
k = k if name_callback is None else name_callback(k)
v = Value(v, depth+1)
try:
# TODO -- right here we should check some flag or something to
# see if lists should render objects
if k is None:
s_body.append("{}".format(v))
else:
s_body.append("{}: {}".format(k, v))
except RuntimeError as e:
# I've never gotten this to work
s_body.append("{}: ... Recursion error ...".format(k))
except UnicodeError as e:
print(v.val)
print(type(v.val))
s_body = ",\n".join(s_body)
s_body = self._add_indent(s_body, indent + 1)
s.append(s_body)
s.append("{}".format(self._add_indent(right_paren, indent)))
return "\n".join(s) | python | def _str_iterator(self, iterator, name_callback=None, prefix="\n", left_paren='[', right_paren=']', depth=0):
'''
turn an iteratable value into a string representation
iterator -- iterator -- the value to be iterated through
name_callback -- callback -- if not None, a function that will take the key of each iteration
prefix -- string -- what will be prepended to the generated value
left_paren -- string -- what will open the generated value
right_paren -- string -- what will close the generated value
depth -- integer -- how deep into recursion we are
return -- string
'''
indent = 1 if depth > 0 else 0
s = []
s.append('{}{}'.format(prefix, self._add_indent(left_paren, indent)))
s_body = []
for k, v in iterator:
k = k if name_callback is None else name_callback(k)
v = Value(v, depth+1)
try:
# TODO -- right here we should check some flag or something to
# see if lists should render objects
if k is None:
s_body.append("{}".format(v))
else:
s_body.append("{}: {}".format(k, v))
except RuntimeError as e:
# I've never gotten this to work
s_body.append("{}: ... Recursion error ...".format(k))
except UnicodeError as e:
print(v.val)
print(type(v.val))
s_body = ",\n".join(s_body)
s_body = self._add_indent(s_body, indent + 1)
s.append(s_body)
s.append("{}".format(self._add_indent(right_paren, indent)))
return "\n".join(s) | turn an iteratable value into a string representation
iterator -- iterator -- the value to be iterated through
name_callback -- callback -- if not None, a function that will take the key of each iteration
prefix -- string -- what will be prepended to the generated value
left_paren -- string -- what will open the generated value
right_paren -- string -- what will close the generated value
depth -- integer -- how deep into recursion we are
return -- string | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/value.py#L346-L391 |
Jaymon/pout | pout/value.py | Value._add_indent | def _add_indent(self, val, indent_count):
'''
add whitespace to the beginning of each line of val
link -- http://code.activestate.com/recipes/66055-changing-the-indentation-of-a-multi-line-string/
val -- string
indent -- integer -- how much whitespace we want in front of each line of val
return -- string -- val with more whitespace
'''
if isinstance(val, Value):
val = val.string_value()
return String(val).indent(indent_count) | python | def _add_indent(self, val, indent_count):
'''
add whitespace to the beginning of each line of val
link -- http://code.activestate.com/recipes/66055-changing-the-indentation-of-a-multi-line-string/
val -- string
indent -- integer -- how much whitespace we want in front of each line of val
return -- string -- val with more whitespace
'''
if isinstance(val, Value):
val = val.string_value()
return String(val).indent(indent_count) | add whitespace to the beginning of each line of val
link -- http://code.activestate.com/recipes/66055-changing-the-indentation-of-a-multi-line-string/
val -- string
indent -- integer -- how much whitespace we want in front of each line of val
return -- string -- val with more whitespace | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/value.py#L393-L407 |
Jaymon/pout | pout/value.py | ObjectValue._getattr | def _getattr(self, val, key, default_val):
"""wrapper around global getattr(...) method that suppresses any exception raised"""
try:
ret = getattr(val, key, default_val)
except Exception as e:
logger.exception(e)
ret = default_val
return ret | python | def _getattr(self, val, key, default_val):
"""wrapper around global getattr(...) method that suppresses any exception raised"""
try:
ret = getattr(val, key, default_val)
except Exception as e:
logger.exception(e)
ret = default_val
return ret | wrapper around global getattr(...) method that suppresses any exception raised | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/value.py#L549-L558 |
Jaymon/pout | pout/value.py | ObjectValue._get_name | def _get_name(self, val, src_file, default='Unknown'):
'''
get the full namespaced (module + class) name of the val object
since -- 6-28-12
val -- mixed -- the value (everything is an object) object
default -- string -- the default name if a decent name can't be found programmatically
return -- string -- the full.module.Name
'''
module_name = ''
if src_file:
module_name = '{}.'.format(self._getattr(val, '__module__', default)).lstrip('.')
class_name = self._getattr(val, '__name__', None)
if not class_name:
class_name = default
cls = self._getattr(val, '__class__', None)
if cls:
class_name = self._getattr(cls, '__name__', default)
full_name = "{}{}".format(module_name, class_name)
return full_name | python | def _get_name(self, val, src_file, default='Unknown'):
'''
get the full namespaced (module + class) name of the val object
since -- 6-28-12
val -- mixed -- the value (everything is an object) object
default -- string -- the default name if a decent name can't be found programmatically
return -- string -- the full.module.Name
'''
module_name = ''
if src_file:
module_name = '{}.'.format(self._getattr(val, '__module__', default)).lstrip('.')
class_name = self._getattr(val, '__name__', None)
if not class_name:
class_name = default
cls = self._getattr(val, '__class__', None)
if cls:
class_name = self._getattr(cls, '__name__', default)
full_name = "{}{}".format(module_name, class_name)
return full_name | get the full namespaced (module + class) name of the val object
since -- 6-28-12
val -- mixed -- the value (everything is an object) object
default -- string -- the default name if a decent name can't be found programmatically
return -- string -- the full.module.Name | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/value.py#L560-L584 |
Jaymon/pout | pout/value.py | ObjectValue._get_src_file | def _get_src_file(self, val, default='Unknown'):
'''
return the source file path
since -- 7-19-12
val -- mixed -- the value whose path you want
return -- string -- the path, or something like 'Unknown' if you can't find the path
'''
path = default
try:
# http://stackoverflow.com/questions/6761337/inspect-getfile-vs-inspect-getsourcefile
# first try and get the actual source file
source_file = inspect.getsourcefile(val)
if not source_file:
# get the raw file since val doesn't have a source file (could be a .pyc or .so file)
source_file = inspect.getfile(val)
if source_file:
path = os.path.realpath(source_file)
except TypeError as e:
path = default
return path | python | def _get_src_file(self, val, default='Unknown'):
'''
return the source file path
since -- 7-19-12
val -- mixed -- the value whose path you want
return -- string -- the path, or something like 'Unknown' if you can't find the path
'''
path = default
try:
# http://stackoverflow.com/questions/6761337/inspect-getfile-vs-inspect-getsourcefile
# first try and get the actual source file
source_file = inspect.getsourcefile(val)
if not source_file:
# get the raw file since val doesn't have a source file (could be a .pyc or .so file)
source_file = inspect.getfile(val)
if source_file:
path = os.path.realpath(source_file)
except TypeError as e:
path = default
return path | return the source file path
since -- 7-19-12
val -- mixed -- the value whose path you want
return -- string -- the path, or something like 'Unknown' if you can't find the path | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/value.py#L586-L612 |
Jaymon/pout | pout/environ.py | handle_decode_replace | def handle_decode_replace(e):
"""this handles replacing bad characters when printing out
http://www.programcreek.com/python/example/3643/codecs.register_error
http://bioportal.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/codecs/index.html
https://pymotw.com/2/codecs/
"""
count = e.end - e.start
#return "." * count, e.end
global ENCODING_REPLACE_CHAR
return ENCODING_REPLACE_CHAR * count, e.end | python | def handle_decode_replace(e):
"""this handles replacing bad characters when printing out
http://www.programcreek.com/python/example/3643/codecs.register_error
http://bioportal.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/codecs/index.html
https://pymotw.com/2/codecs/
"""
count = e.end - e.start
#return "." * count, e.end
global ENCODING_REPLACE_CHAR
return ENCODING_REPLACE_CHAR * count, e.end | this handles replacing bad characters when printing out
http://www.programcreek.com/python/example/3643/codecs.register_error
http://bioportal.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/codecs/index.html
https://pymotw.com/2/codecs/ | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/environ.py#L40-L51 |
elsampsa/valkka-live | valkka/live/container/root.py | RootVideoContainer.makeWidget | def makeWidget(self, qscreen: QtGui.QScreen):
# (re)create the widget, do the same for children
# how children are placed on the parent widget, depends on the subclass
self.window = self.ContainerWindow(
self.signals, self.title, self.parent)
# send to correct x-screen
self.window.show()
self.window.windowHandle().setScreen(qscreen)
self.n_xscreen = self.gpu_handler.getXScreenNum(qscreen) # the correct x-screen number must be passed upstream, to the VideoContainer
# continue window / widget construction in the correct x screen
self.main_widget = self.ContainerWidget(self.window)
self.main_layout = QtWidgets.QVBoxLayout(self.main_widget)
self.window.setCentralWidget(self.main_widget)
# add here any extra turf to the widget you want in addition to the
# grid
# create the grid
self.grid_widget = self.GridWidget(self.main_widget)
self.main_layout.addWidget(self.grid_widget)
self.grid_layout = QtWidgets.QGridLayout(self.grid_widget)
self.grid_layout.setHorizontalSpacing(2)
self.grid_layout.setVerticalSpacing(2)
# ( int left, int top, int right, int bottom )
self.grid_layout.setContentsMargins(0, 0, 0, 0)
class ScreenMenu(QuickMenu):
title = "Change Screen"
elements = [
QuickMenuElement(title="Screen 1"),
QuickMenuElement(title="Screen 2")
]
""" TODO: activate after gpu-hopping has been debugged
self.screenmenu = ScreenMenu(self.window)
self.screenmenu.screen_1.triggered.connect(self.test_slot)
self.screenmenu.screen_2.triggered.connect(self.test_slot)
"""
if (len(self.gpu_handler.true_screens) > 1):
# so, there's more than a single x screen: create a button for
# changing x-screens
self.button = QtWidgets.QPushButton(
"Change Screen", self.main_widget)
self.main_layout.addWidget(self.button)
self.button.setSizePolicy(
QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Minimum)
self.button.clicked.connect(self.change_xscreen_slot)
self.placeChildren() | python | def makeWidget(self, qscreen: QtGui.QScreen):
# (re)create the widget, do the same for children
# how children are placed on the parent widget, depends on the subclass
self.window = self.ContainerWindow(
self.signals, self.title, self.parent)
# send to correct x-screen
self.window.show()
self.window.windowHandle().setScreen(qscreen)
self.n_xscreen = self.gpu_handler.getXScreenNum(qscreen) # the correct x-screen number must be passed upstream, to the VideoContainer
# continue window / widget construction in the correct x screen
self.main_widget = self.ContainerWidget(self.window)
self.main_layout = QtWidgets.QVBoxLayout(self.main_widget)
self.window.setCentralWidget(self.main_widget)
# add here any extra turf to the widget you want in addition to the
# grid
# create the grid
self.grid_widget = self.GridWidget(self.main_widget)
self.main_layout.addWidget(self.grid_widget)
self.grid_layout = QtWidgets.QGridLayout(self.grid_widget)
self.grid_layout.setHorizontalSpacing(2)
self.grid_layout.setVerticalSpacing(2)
# ( int left, int top, int right, int bottom )
self.grid_layout.setContentsMargins(0, 0, 0, 0)
class ScreenMenu(QuickMenu):
title = "Change Screen"
elements = [
QuickMenuElement(title="Screen 1"),
QuickMenuElement(title="Screen 2")
]
""" TODO: activate after gpu-hopping has been debugged
self.screenmenu = ScreenMenu(self.window)
self.screenmenu.screen_1.triggered.connect(self.test_slot)
self.screenmenu.screen_2.triggered.connect(self.test_slot)
"""
if (len(self.gpu_handler.true_screens) > 1):
# so, there's more than a single x screen: create a button for
# changing x-screens
self.button = QtWidgets.QPushButton(
"Change Screen", self.main_widget)
self.main_layout.addWidget(self.button)
self.button.setSizePolicy(
QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Minimum)
self.button.clicked.connect(self.change_xscreen_slot)
self.placeChildren() | TODO: activate after gpu-hopping has been debugged
self.screenmenu = ScreenMenu(self.window)
self.screenmenu.screen_1.triggered.connect(self.test_slot)
self.screenmenu.screen_2.triggered.connect(self.test_slot) | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/root.py#L107-L160 |
elsampsa/valkka-live | valkka/live/container/root.py | RootVideoContainer.close | def close(self):
"""Called by the main gui to close the containers. Called also when the container widget is closed
Closed by clicking the window: goes through self.close_slot
Closed programmatically: use this method directly
"""
if (self.closed):
return
print(self.pre, "close")
for child in self.children:
child.close()
self.openglthread = None
self.gpu_handler = None
self.closed = True
self.window.unSetPropagate() # we don't want the window to send the close signal .. which would call this *again* (through close_slot)
self.window.close() | python | def close(self):
"""Called by the main gui to close the containers. Called also when the container widget is closed
Closed by clicking the window: goes through self.close_slot
Closed programmatically: use this method directly
"""
if (self.closed):
return
print(self.pre, "close")
for child in self.children:
child.close()
self.openglthread = None
self.gpu_handler = None
self.closed = True
self.window.unSetPropagate() # we don't want the window to send the close signal .. which would call this *again* (through close_slot)
self.window.close() | Called by the main gui to close the containers. Called also when the container widget is closed
Closed by clicking the window: goes through self.close_slot
Closed programmatically: use this method directly | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/root.py#L180-L196 |
elsampsa/valkka-live | valkka/live/container/root.py | RootVideoContainer.serialize | def serialize(self):
"""Serialize information about the widget: coordinates, size, which cameras are selected.
"""
ids = []
for child in self.children:
device = child.getDevice()
if device:
ids.append(device._id) # e.g. DataModel.RTSPCameraDevice._id
else:
ids.append(None)
# gather all information to re-construct this RootVideoContainer
dic = { # these are used when re-instantiating the view
"classname": self.__class__.__name__,
"kwargs": { # parameters that we're used to instantiate this class
"title" : self.title,
"n_xscreen" : self.n_xscreen,
"child_class" : self.child_class,
"child_class_pars" : self.get_child_class_pars() # serialize only relevant child class pars
},
# these parameters are used by deserialize
"x": self.window.x(),
"y": self.window.y(),
"width": self.window.width(),
"height": self.window.height(),
"ids": ids
}
return dic | python | def serialize(self):
"""Serialize information about the widget: coordinates, size, which cameras are selected.
"""
ids = []
for child in self.children:
device = child.getDevice()
if device:
ids.append(device._id) # e.g. DataModel.RTSPCameraDevice._id
else:
ids.append(None)
# gather all information to re-construct this RootVideoContainer
dic = { # these are used when re-instantiating the view
"classname": self.__class__.__name__,
"kwargs": { # parameters that we're used to instantiate this class
"title" : self.title,
"n_xscreen" : self.n_xscreen,
"child_class" : self.child_class,
"child_class_pars" : self.get_child_class_pars() # serialize only relevant child class pars
},
# these parameters are used by deserialize
"x": self.window.x(),
"y": self.window.y(),
"width": self.window.width(),
"height": self.window.height(),
"ids": ids
}
return dic | Serialize information about the widget: coordinates, size, which cameras are selected. | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/container/root.py#L201-L229 |
elsampsa/valkka-live | valkka/mvision/movement/base.py | MovementDetector.reset | def reset(self):
"""Reset analyzer state
"""
self.prevframe = None
self.wasmoving = False
self.t0 = 0
self.ismoving = False | python | def reset(self):
"""Reset analyzer state
"""
self.prevframe = None
self.wasmoving = False
self.t0 = 0
self.ismoving = False | Reset analyzer state | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/movement/base.py#L68-L74 |
elsampsa/valkka-live | valkka/mvision/movement/base.py | MVisionProcess.getWidget | def getWidget(self):
"""Some ideas for your widget:
- Textual information (alert, license place number)
- Check boxes : if checked, send e-mail to your mom when the analyzer spots something
- .. or send an sms to yourself
- You can include the cv2.imshow window to the widget to see how the analyzer proceeds
"""
widget = QtWidgets.QLabel("NO MOVEMENT YET")
widget.setStyleSheet(style.detector_test)
self.signals.start_move.connect(lambda : widget.setText("MOVEMENT START"))
self.signals.stop_move. connect(lambda : widget.setText("MOVEMENT STOP"))
return widget | python | def getWidget(self):
"""Some ideas for your widget:
- Textual information (alert, license place number)
- Check boxes : if checked, send e-mail to your mom when the analyzer spots something
- .. or send an sms to yourself
- You can include the cv2.imshow window to the widget to see how the analyzer proceeds
"""
widget = QtWidgets.QLabel("NO MOVEMENT YET")
widget.setStyleSheet(style.detector_test)
self.signals.start_move.connect(lambda : widget.setText("MOVEMENT START"))
self.signals.stop_move. connect(lambda : widget.setText("MOVEMENT STOP"))
return widget | Some ideas for your widget:
- Textual information (alert, license place number)
- Check boxes : if checked, send e-mail to your mom when the analyzer spots something
- .. or send an sms to yourself
- You can include the cv2.imshow window to the widget to see how the analyzer proceeds | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/movement/base.py#L306-L317 |
veripress/veripress | veripress/api/__init__.py | rule | def rule(rules, strict_slashes=False, api_func=None, *args, **kwargs):
"""
Add a API route to the 'api' blueprint.
:param rules: rule string or string list
:param strict_slashes: same to Blueprint.route, but default value is False
:param api_func: a function that returns a JSON serializable object
or a Flask Response, or raises ApiException
:param args: other args that should be passed to Blueprint.route
:param kwargs: other kwargs that should be passed to Blueprint.route
:return:
"""
return url_rule(api_blueprint, rules, strict_slashes=strict_slashes,
view_func=json_api(api_func) if api_func else None,
*args, **kwargs) | python | def rule(rules, strict_slashes=False, api_func=None, *args, **kwargs):
"""
Add a API route to the 'api' blueprint.
:param rules: rule string or string list
:param strict_slashes: same to Blueprint.route, but default value is False
:param api_func: a function that returns a JSON serializable object
or a Flask Response, or raises ApiException
:param args: other args that should be passed to Blueprint.route
:param kwargs: other kwargs that should be passed to Blueprint.route
:return:
"""
return url_rule(api_blueprint, rules, strict_slashes=strict_slashes,
view_func=json_api(api_func) if api_func else None,
*args, **kwargs) | Add a API route to the 'api' blueprint.
:param rules: rule string or string list
:param strict_slashes: same to Blueprint.route, but default value is False
:param api_func: a function that returns a JSON serializable object
or a Flask Response, or raises ApiException
:param args: other args that should be passed to Blueprint.route
:param kwargs: other kwargs that should be passed to Blueprint.route
:return: | https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/api/__init__.py#L80-L94 |
elsampsa/valkka-live | valkka/live/gpuhandler.py | GPUHandler.findXScreens | def findXScreens(self):
qapp = QtCore.QCoreApplication.instance()
if not qapp: # QApplication has not been started
return
screens = qapp.screens()
"""
let's find out which screens are virtual
screen, siblings:
One big virtual desktop:
A [A, B, C]
B [A, B, C]
C [A, B, C]
A & B in one xscreen, C in another:
A [A, B]
B [A, B]
C [C]
"""
virtual_screens = set()
for screen in screens:
# if screen has been deemed as "virtual", don't check its siblings
if (screen not in virtual_screens):
siblings = screen.virtualSiblings()
# remove the current screen under scrutiny from the siblings
# list
virtual_screens.update(set(siblings).difference(set([screen])))
# .. the ones left over are virtual
# print("GPUHandler: findXScreens: virtual screens",virtual_screens)
true_screens = list(set(screens) - virtual_screens)
# sort'em
for screen in true_screens:
self.true_screens.insert(screens.index(screen), screen)
print("GPUHandler: findXScreens: true screens:", self.true_screens) | python | def findXScreens(self):
qapp = QtCore.QCoreApplication.instance()
if not qapp: # QApplication has not been started
return
screens = qapp.screens()
"""
let's find out which screens are virtual
screen, siblings:
One big virtual desktop:
A [A, B, C]
B [A, B, C]
C [A, B, C]
A & B in one xscreen, C in another:
A [A, B]
B [A, B]
C [C]
"""
virtual_screens = set()
for screen in screens:
# if screen has been deemed as "virtual", don't check its siblings
if (screen not in virtual_screens):
siblings = screen.virtualSiblings()
# remove the current screen under scrutiny from the siblings
# list
virtual_screens.update(set(siblings).difference(set([screen])))
# .. the ones left over are virtual
# print("GPUHandler: findXScreens: virtual screens",virtual_screens)
true_screens = list(set(screens) - virtual_screens)
# sort'em
for screen in true_screens:
self.true_screens.insert(screens.index(screen), screen)
print("GPUHandler: findXScreens: true screens:", self.true_screens) | let's find out which screens are virtual
screen, siblings:
One big virtual desktop:
A [A, B, C]
B [A, B, C]
C [A, B, C]
A & B in one xscreen, C in another:
A [A, B]
B [A, B]
C [C] | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gpuhandler.py#L82-L123 |
elsampsa/valkka-live | valkka/live/gui.py | MyGui.readDB | def readDB(self):
"""Datamodel includes the following files: config.dat, devices.dat
"""
self.dm = DataModel(directory = tools.getConfigDir())
if (self.first_start):
print(pre, "readDB : first start")
self.dm.clearAll()
self.dm.saveAll()
# If camera collection is corrupt
if not self.dm.checkCameraCollection():
self.dm.clearCameraCollection() | python | def readDB(self):
"""Datamodel includes the following files: config.dat, devices.dat
"""
self.dm = DataModel(directory = tools.getConfigDir())
if (self.first_start):
print(pre, "readDB : first start")
self.dm.clearAll()
self.dm.saveAll()
# If camera collection is corrupt
if not self.dm.checkCameraCollection():
self.dm.clearCameraCollection() | Datamodel includes the following files: config.dat, devices.dat | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gui.py#L109-L120 |
elsampsa/valkka-live | valkka/live/gui.py | MyGui.generateMethods | def generateMethods(self):
"""Generate some member functions
"""
for i in range(1, 5):
# adds member function grid_ixi_slot(self)
self.make_grid_slot(i, i)
for cl in self.mvision_classes:
self.make_mvision_slot(cl) | python | def generateMethods(self):
"""Generate some member functions
"""
for i in range(1, 5):
# adds member function grid_ixi_slot(self)
self.make_grid_slot(i, i)
for cl in self.mvision_classes:
self.make_mvision_slot(cl) | Generate some member functions | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gui.py#L123-L131 |
elsampsa/valkka-live | valkka/live/gui.py | MyGui.QCapsulate | def QCapsulate(self, widget, name, blocking = False, nude = False):
"""Helper function that encapsulates QWidget into a QMainWindow
"""
class QuickWindow(QtWidgets.QMainWindow):
class Signals(QtCore.QObject):
close = QtCore.Signal()
show = QtCore.Signal()
def __init__(self, blocking = False, parent = None, nude = False):
super().__init__(parent)
self.propagate = True # send signals or not
self.setStyleSheet(style.main_gui)
if (blocking):
self.setWindowModality(QtCore.Qt.ApplicationModal)
if (nude):
# http://doc.qt.io/qt-5/qt.html#WindowType-enum
# TODO: create a widget for a proper splashscreen (omitting X11 and centering manually)
# self.setWindowFlags(QtCore.Qt.Popup) # Qt 5.9+ : setFlags()
# self.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.WindowStaysOnTopHint)
self.setWindowFlags(QtCore.Qt.Dialog)
self.signals = self.Signals()
def closeEvent(self, e):
if (self.propagate):
self.signals.close.emit()
e.accept()
def showEvent(self, e):
if (self.propagate):
self.signals.show.emit()
e.accept()
def setPropagate(self):
self.propagate = True
def unSetPropagate(self):
self.propagate = False
win = QuickWindow(blocking = blocking, nude = nude)
win.setCentralWidget(widget)
win.setLayout(QtWidgets.QHBoxLayout())
win.setWindowTitle(name)
return win | python | def QCapsulate(self, widget, name, blocking = False, nude = False):
"""Helper function that encapsulates QWidget into a QMainWindow
"""
class QuickWindow(QtWidgets.QMainWindow):
class Signals(QtCore.QObject):
close = QtCore.Signal()
show = QtCore.Signal()
def __init__(self, blocking = False, parent = None, nude = False):
super().__init__(parent)
self.propagate = True # send signals or not
self.setStyleSheet(style.main_gui)
if (blocking):
self.setWindowModality(QtCore.Qt.ApplicationModal)
if (nude):
# http://doc.qt.io/qt-5/qt.html#WindowType-enum
# TODO: create a widget for a proper splashscreen (omitting X11 and centering manually)
# self.setWindowFlags(QtCore.Qt.Popup) # Qt 5.9+ : setFlags()
# self.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.WindowStaysOnTopHint)
self.setWindowFlags(QtCore.Qt.Dialog)
self.signals = self.Signals()
def closeEvent(self, e):
if (self.propagate):
self.signals.close.emit()
e.accept()
def showEvent(self, e):
if (self.propagate):
self.signals.show.emit()
e.accept()
def setPropagate(self):
self.propagate = True
def unSetPropagate(self):
self.propagate = False
win = QuickWindow(blocking = blocking, nude = nude)
win.setCentralWidget(widget)
win.setLayout(QtWidgets.QHBoxLayout())
win.setWindowTitle(name)
return win | Helper function that encapsulates QWidget into a QMainWindow | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gui.py#L134-L180 |
elsampsa/valkka-live | valkka/live/gui.py | MyGui.QTabCapsulate | def QTabCapsulate(self, name, widget_list, blocking = False):
"""Helper function that encapsulates QWidget into a QMainWindow
:param widget_list: List of tuples : [(widget,"name"), (widget,"name"), ..]
"""
class QuickWindow(QtWidgets.QMainWindow):
class Signals(QtCore.QObject):
close = QtCore.Signal()
show = QtCore.Signal()
def __init__(self, blocking = False, parent = None):
super().__init__(parent)
self.propagate = True # send signals or not
self.setStyleSheet(style.main_gui)
if (blocking):
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.signals = self.Signals()
self.tab = QtWidgets.QTabWidget()
self.setCentralWidget(self.tab)
self.setLayout(QtWidgets.QHBoxLayout())
def closeEvent(self, e):
if (self.propagate):
self.signals.close.emit()
e.accept()
def showEvent(self, e):
if (self.propagate):
self.signals.show.emit()
e.accept()
def setPropagate(self):
self.propagate = True
def unSetPropagate(self):
self.propagate = False
win = QuickWindow(blocking = blocking)
win.setWindowTitle(name)
for w in widget_list:
win.tab.addTab(w[0], w[1])
return win | python | def QTabCapsulate(self, name, widget_list, blocking = False):
"""Helper function that encapsulates QWidget into a QMainWindow
:param widget_list: List of tuples : [(widget,"name"), (widget,"name"), ..]
"""
class QuickWindow(QtWidgets.QMainWindow):
class Signals(QtCore.QObject):
close = QtCore.Signal()
show = QtCore.Signal()
def __init__(self, blocking = False, parent = None):
super().__init__(parent)
self.propagate = True # send signals or not
self.setStyleSheet(style.main_gui)
if (blocking):
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.signals = self.Signals()
self.tab = QtWidgets.QTabWidget()
self.setCentralWidget(self.tab)
self.setLayout(QtWidgets.QHBoxLayout())
def closeEvent(self, e):
if (self.propagate):
self.signals.close.emit()
e.accept()
def showEvent(self, e):
if (self.propagate):
self.signals.show.emit()
e.accept()
def setPropagate(self):
self.propagate = True
def unSetPropagate(self):
self.propagate = False
win = QuickWindow(blocking = blocking)
win.setWindowTitle(name)
for w in widget_list:
win.tab.addTab(w[0], w[1])
return win | Helper function that encapsulates QWidget into a QMainWindow
:param widget_list: List of tuples : [(widget,"name"), (widget,"name"), ..] | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gui.py#L183-L229 |
elsampsa/valkka-live | valkka/live/gui.py | MyGui.updateCameraTree | def updateCameraTree(self):
self.treelist.reset_()
self.server = ServerListItem(
name = "Localhost", ip = "127.0.0.1", parent = self.root)
"""
self.server1 = ServerListItem(
name="First Server", ip="192.168.1.20", parent=self.root)
"""
"""
self.camera1 = RTSPCameraListItem(camera=RTSPCameraDevice(
ip="192.168.1.4", username="admin", password="1234"), parent=self.server1)
self.camera2 = RTSPCameraListItem(camera=RTSPCameraDevice(
ip="192.168.1.4", username="admin", password="1234"), parent=self.server1)
"""
devices = []
for row in self.dm.camera_collection.get():
# print(pre, "makeCameraTree : row", row)
if (row["classname"] == DataModel.RTSPCameraRow.__name__):
row.pop("classname")
devices.append(
RTSPCameraListItem(
camera = DataModel.RTSPCameraDevice(**row),
parent = self.server
)
)
elif (row["classname"] == DataModel.USBCameraRow.__name__):
row.pop("classname")
devices.append(
USBCameraListItem(
camera = DataModel.USBCameraDevice(**row),
parent = self.server
)
)
self.treelist.update()
self.treelist.expandAll() | python | def updateCameraTree(self):
self.treelist.reset_()
self.server = ServerListItem(
name = "Localhost", ip = "127.0.0.1", parent = self.root)
"""
self.server1 = ServerListItem(
name="First Server", ip="192.168.1.20", parent=self.root)
"""
"""
self.camera1 = RTSPCameraListItem(camera=RTSPCameraDevice(
ip="192.168.1.4", username="admin", password="1234"), parent=self.server1)
self.camera2 = RTSPCameraListItem(camera=RTSPCameraDevice(
ip="192.168.1.4", username="admin", password="1234"), parent=self.server1)
"""
devices = []
for row in self.dm.camera_collection.get():
# print(pre, "makeCameraTree : row", row)
if (row["classname"] == DataModel.RTSPCameraRow.__name__):
row.pop("classname")
devices.append(
RTSPCameraListItem(
camera = DataModel.RTSPCameraDevice(**row),
parent = self.server
)
)
elif (row["classname"] == DataModel.USBCameraRow.__name__):
row.pop("classname")
devices.append(
USBCameraListItem(
camera = DataModel.USBCameraDevice(**row),
parent = self.server
)
)
self.treelist.update()
self.treelist.expandAll() | self.server1 = ServerListItem(
name="First Server", ip="192.168.1.20", parent=self.root) | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gui.py#L312-L349 |
elsampsa/valkka-live | valkka/live/gui.py | MyGui.makeLogic | def makeLogic(self):
# *** When camera list has been closed, re-create the cameralist tree and update filterchains ***
# self.manage_cameras_win.signals.close.connect(self.updateCameraTree) # now put into save_camera_config_slot
# self.manage_cameras_win.signals.close.connect(self.filterchain_group.update) # TODO: use this once fixed
# self.manage_cameras_win.signals.close.connect(self.filterchain_group.read) # TODO: eh.. lets be sure of this .. (are we releasing slots in the LiveThread etc.)
# self.manage_cameras_win.signals.close.connect(self.save_camera_config_slot)
# self.manage_memory_container.signals.save.connect(self.save_memory_conf_slot)
# *** Menu bar connections ***
# the self.filemenu.exit attribute was autogenerated
self.filemenu.exit. triggered.connect(self.exit_slot)
self.filemenu.save_window_layout. triggered.connect(
self.save_window_layout_slot)
self.filemenu.load_window_layout. triggered.connect(
self.load_window_layout_slot)
"""
self.configmenu.manage_cameras. triggered.connect(
self.manage_cameras_slot)
self.configmenu.memory_usage. triggered.connect(
self.memory_usage_slot)
"""
self.configmenu.configuration_dialog.triggered.connect(self.config_dialog_slot)
self.viewmenu.camera_list. triggered.connect(self.camera_list_slot)
self.aboutmenu.about_valkka_live. triggered.connect(self.about_slot)
# *** Connect autogenerated menu calls into autogenerated slot functions ***
for i in range(1, 5):
# gets member function grid_ixi_slot
slot_func = getattr(self, "grid_%ix%i_slot" % (i, i))
# gets member function grid_ixi from self.viewmenu.video_grid
menu_func = getattr(self.viewmenu.video_grid,
"grid_%ix%i" % (i, i))
menu_func.triggered.connect(slot_func)
# i.e., like this : self.viewmenu.video_grid.grid_1x1.triggered.connect(slot_func)
# *** autogenerated machine vision menu and slots ***
for cl in self.mvision_classes:
getattr(self.mvisionmenu,cl.name).triggered.connect(getattr(self,cl.name+"_slot")) | python | def makeLogic(self):
# *** When camera list has been closed, re-create the cameralist tree and update filterchains ***
# self.manage_cameras_win.signals.close.connect(self.updateCameraTree) # now put into save_camera_config_slot
# self.manage_cameras_win.signals.close.connect(self.filterchain_group.update) # TODO: use this once fixed
# self.manage_cameras_win.signals.close.connect(self.filterchain_group.read) # TODO: eh.. lets be sure of this .. (are we releasing slots in the LiveThread etc.)
# self.manage_cameras_win.signals.close.connect(self.save_camera_config_slot)
# self.manage_memory_container.signals.save.connect(self.save_memory_conf_slot)
# *** Menu bar connections ***
# the self.filemenu.exit attribute was autogenerated
self.filemenu.exit. triggered.connect(self.exit_slot)
self.filemenu.save_window_layout. triggered.connect(
self.save_window_layout_slot)
self.filemenu.load_window_layout. triggered.connect(
self.load_window_layout_slot)
"""
self.configmenu.manage_cameras. triggered.connect(
self.manage_cameras_slot)
self.configmenu.memory_usage. triggered.connect(
self.memory_usage_slot)
"""
self.configmenu.configuration_dialog.triggered.connect(self.config_dialog_slot)
self.viewmenu.camera_list. triggered.connect(self.camera_list_slot)
self.aboutmenu.about_valkka_live. triggered.connect(self.about_slot)
# *** Connect autogenerated menu calls into autogenerated slot functions ***
for i in range(1, 5):
# gets member function grid_ixi_slot
slot_func = getattr(self, "grid_%ix%i_slot" % (i, i))
# gets member function grid_ixi from self.viewmenu.video_grid
menu_func = getattr(self.viewmenu.video_grid,
"grid_%ix%i" % (i, i))
menu_func.triggered.connect(slot_func)
# i.e., like this : self.viewmenu.video_grid.grid_1x1.triggered.connect(slot_func)
# *** autogenerated machine vision menu and slots ***
for cl in self.mvision_classes:
getattr(self.mvisionmenu,cl.name).triggered.connect(getattr(self,cl.name+"_slot")) | self.configmenu.manage_cameras. triggered.connect(
self.manage_cameras_slot)
self.configmenu.memory_usage. triggered.connect(
self.memory_usage_slot) | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gui.py#L352-L395 |
elsampsa/valkka-live | valkka/live/gui.py | MyGui.serializeContainers | def serializeContainers(self):
"""Serializes the current view of open video grids (i.e. the view)
"""
""" each serialized container looks like this:
dic={# these are used when re-instantiating the view
"classname" : self.__class__.__name__,
"kwargs" : {}, # parameters that we're used to instantiate this class
# these parameters are used by deserialize
"x" : self.window.x(),
"y" : self.window.y(),
"width" : self.window.width(),
"height" : self.window.height(),
"streams" : streams
}
"""
container_list = []
mvision_container_list = []
for container in self.containers:
print("gui: serialize containers : container=", container)
container_list.append(container.serialize())
for container in self.mvision_containers:
mvision_container_list.append(container.serialize())
return {"container_list" : container_list, "mvision_container_list" : mvision_container_list} | python | def serializeContainers(self):
"""Serializes the current view of open video grids (i.e. the view)
"""
""" each serialized container looks like this:
dic={# these are used when re-instantiating the view
"classname" : self.__class__.__name__,
"kwargs" : {}, # parameters that we're used to instantiate this class
# these parameters are used by deserialize
"x" : self.window.x(),
"y" : self.window.y(),
"width" : self.window.width(),
"height" : self.window.height(),
"streams" : streams
}
"""
container_list = []
mvision_container_list = []
for container in self.containers:
print("gui: serialize containers : container=", container)
container_list.append(container.serialize())
for container in self.mvision_containers:
mvision_container_list.append(container.serialize())
return {"container_list" : container_list, "mvision_container_list" : mvision_container_list} | Serializes the current view of open video grids (i.e. the view) | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gui.py#L414-L440 |
elsampsa/valkka-live | valkka/live/gui.py | MyGui.startProcesses | def startProcesses(self):
"""Create and start python multiprocesses
Starting a multiprocess creates a process fork.
In theory, there should be no problem in first starting the multithreading environment and after that perform forks (only the thread requestin the fork is copied), but in practice, all kinds of weird behaviour arises.
Read all about it in here : http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them
"""
self.process_map = {} # each key is a list of started multiprocesses
# self.process_avail = {} # count instances
for mvision_class in self.mvision_classes:
name = mvision_class.name
tag = mvision_class.tag
num = mvision_class.max_instances
if (tag not in self.process_map):
self.process_map[tag] = []
# self.process_avail[tag] = num
for n in range(0, num):
p = mvision_class()
p.start()
self.process_map[tag].append(p) | python | def startProcesses(self):
"""Create and start python multiprocesses
Starting a multiprocess creates a process fork.
In theory, there should be no problem in first starting the multithreading environment and after that perform forks (only the thread requestin the fork is copied), but in practice, all kinds of weird behaviour arises.
Read all about it in here : http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them
"""
self.process_map = {} # each key is a list of started multiprocesses
# self.process_avail = {} # count instances
for mvision_class in self.mvision_classes:
name = mvision_class.name
tag = mvision_class.tag
num = mvision_class.max_instances
if (tag not in self.process_map):
self.process_map[tag] = []
# self.process_avail[tag] = num
for n in range(0, num):
p = mvision_class()
p.start()
self.process_map[tag].append(p) | Create and start python multiprocesses
Starting a multiprocess creates a process fork.
In theory, there should be no problem in first starting the multithreading environment and after that perform forks (only the thread requestin the fork is copied), but in practice, all kinds of weird behaviour arises.
Read all about it in here : http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gui.py#L487-L509 |
elsampsa/valkka-live | valkka/live/gui.py | MyGui.make_grid_slot | def make_grid_slot(self, n, m):
"""Create a n x m video grid, show it and add it to the list of video containers
"""
def slot_func():
cont = container.VideoContainerNxM(gpu_handler=self.gpu_handler,
filterchain_group=self.filterchain_group,
n_dim=n,
m_dim=m)
cont.signals.closing.connect(self.rem_container_slot)
self.containers.append(cont)
setattr(self, "grid_%ix%i_slot" % (n, m), slot_func) | python | def make_grid_slot(self, n, m):
"""Create a n x m video grid, show it and add it to the list of video containers
"""
def slot_func():
cont = container.VideoContainerNxM(gpu_handler=self.gpu_handler,
filterchain_group=self.filterchain_group,
n_dim=n,
m_dim=m)
cont.signals.closing.connect(self.rem_container_slot)
self.containers.append(cont)
setattr(self, "grid_%ix%i_slot" % (n, m), slot_func) | Create a n x m video grid, show it and add it to the list of video containers | https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/live/gui.py#L650-L660 |
Jaymon/pout | pout/__main__.py | main_inject | def main_inject(args):
"""
mapped to pout.inject on the command line, makes it easy to make pout global
without having to actually import it in your python environment
.. since:: 2018-08-13
:param args: Namespace, the parsed CLI arguments passed into the application
:returns: int, the return code of the CLI
"""
ret = 0
try:
filepath = SiteCustomizeFile()
if filepath.is_injected():
logger.info("Pout has already been injected into {}".format(filepath))
else:
if filepath.inject():
logger.info("Injected pout into {}".format(filepath))
else:
logger.info("Failed to inject pout into {}".format(filepath))
except IOError as e:
ret = 1
logger.info(str(e))
return ret | python | def main_inject(args):
"""
mapped to pout.inject on the command line, makes it easy to make pout global
without having to actually import it in your python environment
.. since:: 2018-08-13
:param args: Namespace, the parsed CLI arguments passed into the application
:returns: int, the return code of the CLI
"""
ret = 0
try:
filepath = SiteCustomizeFile()
if filepath.is_injected():
logger.info("Pout has already been injected into {}".format(filepath))
else:
if filepath.inject():
logger.info("Injected pout into {}".format(filepath))
else:
logger.info("Failed to inject pout into {}".format(filepath))
except IOError as e:
ret = 1
logger.info(str(e))
return ret | mapped to pout.inject on the command line, makes it easy to make pout global
without having to actually import it in your python environment
.. since:: 2018-08-13
:param args: Namespace, the parsed CLI arguments passed into the application
:returns: int, the return code of the CLI | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__main__.py#L68-L95 |
Jaymon/pout | pout/__main__.py | main_info | def main_info(args):
"""Just prints out info about the pout installation
.. since:: 2018-08-20
:param args: Namespace, the parsed CLI arguments passed into the application
:returns: int, the return code of the CLI
"""
if args.site_packages:
logger.info(SitePackagesDir())
else:
logger.info("Python executable: {}".format(sys.executable))
logger.info("Python version: {}".format(platform.python_version()))
logger.info("Python site-packages: {}".format(SitePackagesDir()))
logger.info("Python sitecustomize: {}".format(SiteCustomizeFile()))
# https://stackoverflow.com/questions/4152963/get-the-name-of-current-script-with-python
#logger.info("Pout executable: {}".format(subprocess.check_output(["which", "pout"])))
logger.info("Pout executable: {}".format(os.path.abspath(os.path.expanduser(str(sys.argv[0])))))
logger.info("Pout version: {}".format(pout.__version__))
filepath = SiteCustomizeFile()
logger.info("Pout injected: {}".format(filepath.is_injected())) | python | def main_info(args):
"""Just prints out info about the pout installation
.. since:: 2018-08-20
:param args: Namespace, the parsed CLI arguments passed into the application
:returns: int, the return code of the CLI
"""
if args.site_packages:
logger.info(SitePackagesDir())
else:
logger.info("Python executable: {}".format(sys.executable))
logger.info("Python version: {}".format(platform.python_version()))
logger.info("Python site-packages: {}".format(SitePackagesDir()))
logger.info("Python sitecustomize: {}".format(SiteCustomizeFile()))
# https://stackoverflow.com/questions/4152963/get-the-name-of-current-script-with-python
#logger.info("Pout executable: {}".format(subprocess.check_output(["which", "pout"])))
logger.info("Pout executable: {}".format(os.path.abspath(os.path.expanduser(str(sys.argv[0])))))
logger.info("Pout version: {}".format(pout.__version__))
filepath = SiteCustomizeFile()
logger.info("Pout injected: {}".format(filepath.is_injected())) | Just prints out info about the pout installation
.. since:: 2018-08-20
:param args: Namespace, the parsed CLI arguments passed into the application
:returns: int, the return code of the CLI | https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__main__.py#L98-L120 |
benjamin-hodgson/Contexts | src/contexts/tools.py | catch | def catch(func, *args, **kwargs):
"""
Call the supplied function with the supplied arguments,
catching and returning any exception that it throws.
Arguments:
func: the function to run.
*args: positional arguments to pass into the function.
**kwargs: keyword arguments to pass into the function.
Returns:
If the function throws an exception, return the exception.
If the function does not throw an exception, return None.
"""
try:
func(*args, **kwargs)
except Exception as e:
return e | python | def catch(func, *args, **kwargs):
"""
Call the supplied function with the supplied arguments,
catching and returning any exception that it throws.
Arguments:
func: the function to run.
*args: positional arguments to pass into the function.
**kwargs: keyword arguments to pass into the function.
Returns:
If the function throws an exception, return the exception.
If the function does not throw an exception, return None.
"""
try:
func(*args, **kwargs)
except Exception as e:
return e | Call the supplied function with the supplied arguments,
catching and returning any exception that it throws.
Arguments:
func: the function to run.
*args: positional arguments to pass into the function.
**kwargs: keyword arguments to pass into the function.
Returns:
If the function throws an exception, return the exception.
If the function does not throw an exception, return None. | https://github.com/benjamin-hodgson/Contexts/blob/f5ee6a08aed19ab157158c1fc7752cff18cceb91/src/contexts/tools.py#L6-L22 |
benjamin-hodgson/Contexts | src/contexts/tools.py | time | def time(func, *args, **kwargs):
"""
Call the supplied function with the supplied arguments,
and return the total execution time as a float in seconds.
The precision of the returned value depends on the precision of
`time.time()` on your platform.
Arguments:
func: the function to run.
*args: positional arguments to pass into the function.
**kwargs: keyword arguments to pass into the function.
Returns:
Execution time of the function as a float in seconds.
"""
start_time = time_module.time()
func(*args, **kwargs)
end_time = time_module.time()
return end_time - start_time | python | def time(func, *args, **kwargs):
"""
Call the supplied function with the supplied arguments,
and return the total execution time as a float in seconds.
The precision of the returned value depends on the precision of
`time.time()` on your platform.
Arguments:
func: the function to run.
*args: positional arguments to pass into the function.
**kwargs: keyword arguments to pass into the function.
Returns:
Execution time of the function as a float in seconds.
"""
start_time = time_module.time()
func(*args, **kwargs)
end_time = time_module.time()
return end_time - start_time | Call the supplied function with the supplied arguments,
and return the total execution time as a float in seconds.
The precision of the returned value depends on the precision of
`time.time()` on your platform.
Arguments:
func: the function to run.
*args: positional arguments to pass into the function.
**kwargs: keyword arguments to pass into the function.
Returns:
Execution time of the function as a float in seconds. | https://github.com/benjamin-hodgson/Contexts/blob/f5ee6a08aed19ab157158c1fc7752cff18cceb91/src/contexts/tools.py#L25-L43 |
benjamin-hodgson/Contexts | src/contexts/tools.py | set_trace | def set_trace():
"""Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__."""
# https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py
pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back) | python | def set_trace():
"""Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__."""
# https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py
pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back) | Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__. | https://github.com/benjamin-hodgson/Contexts/blob/f5ee6a08aed19ab157158c1fc7752cff18cceb91/src/contexts/tools.py#L46-L49 |
OpenHydrology/lmoments3 | lmoments3/distr.py | LmomDistrMixin.lmom_fit | def lmom_fit(self, data=[], lmom_ratios=[]):
"""
Fit the distribution function to the given data or given L-moments.
:param data: Data to use in calculating the distribution parameters
:type data: array_like
:param lmom_ratios: L-moments (ratios) l1, l2, t3, t4, .. to use in calculating the distribution parameters
:type lmom_ratios: array_like
:returns: Distribution parameters in `scipy` order, e.g. scale, loc, shape
:rtype: :class:`OrderedDict`
"""
n_min = self.numargs + 2
if len(data) > 0:
if len(data) <= n_min:
raise ValueError("At least {} data points must be provided.".format(n_min))
lmom_ratios = lm.lmom_ratios(data, nmom=n_min)
elif not lmom_ratios:
raise Exception("Either `data` or `lmom_ratios` must be provided.")
elif len(lmom_ratios) < n_min:
raise ValueError("At least {} number of L-moments must be provided.".format(n_min))
return self._lmom_fit(lmom_ratios) | python | def lmom_fit(self, data=[], lmom_ratios=[]):
"""
Fit the distribution function to the given data or given L-moments.
:param data: Data to use in calculating the distribution parameters
:type data: array_like
:param lmom_ratios: L-moments (ratios) l1, l2, t3, t4, .. to use in calculating the distribution parameters
:type lmom_ratios: array_like
:returns: Distribution parameters in `scipy` order, e.g. scale, loc, shape
:rtype: :class:`OrderedDict`
"""
n_min = self.numargs + 2
if len(data) > 0:
if len(data) <= n_min:
raise ValueError("At least {} data points must be provided.".format(n_min))
lmom_ratios = lm.lmom_ratios(data, nmom=n_min)
elif not lmom_ratios:
raise Exception("Either `data` or `lmom_ratios` must be provided.")
elif len(lmom_ratios) < n_min:
raise ValueError("At least {} number of L-moments must be provided.".format(n_min))
return self._lmom_fit(lmom_ratios) | Fit the distribution function to the given data or given L-moments.
:param data: Data to use in calculating the distribution parameters
:type data: array_like
:param lmom_ratios: L-moments (ratios) l1, l2, t3, t4, .. to use in calculating the distribution parameters
:type lmom_ratios: array_like
:returns: Distribution parameters in `scipy` order, e.g. scale, loc, shape
:rtype: :class:`OrderedDict` | https://github.com/OpenHydrology/lmoments3/blob/65934df58cd754f1a38e35dc5ee6c30717e5b94c/lmoments3/distr.py#L44-L65 |
OpenHydrology/lmoments3 | lmoments3/distr.py | LmomDistrMixin.lmom | def lmom(self, *args, nmom=5, **kwds):
"""
Compute the distribution's L-moments, e.g. l1, l2, l3, l4, ..
:param args: Distribution parameters in order of shape(s), loc, scale
:type args: float
:param nmom: Number of moments to calculate
:type nmom: int
:param kwds: Distribution parameters as named arguments. See :attr:`rv_continous.shapes` for names of shape
parameters
:type kwds: float
:returns: List of L-moments
:rtype: list
"""
ratios = self.lmom_ratios(*args, nmom=nmom, **kwds)
moments = ratios[0:2]
moments += [ratio * moments[1] for ratio in ratios[2:]]
return moments | python | def lmom(self, *args, nmom=5, **kwds):
"""
Compute the distribution's L-moments, e.g. l1, l2, l3, l4, ..
:param args: Distribution parameters in order of shape(s), loc, scale
:type args: float
:param nmom: Number of moments to calculate
:type nmom: int
:param kwds: Distribution parameters as named arguments. See :attr:`rv_continous.shapes` for names of shape
parameters
:type kwds: float
:returns: List of L-moments
:rtype: list
"""
ratios = self.lmom_ratios(*args, nmom=nmom, **kwds)
moments = ratios[0:2]
moments += [ratio * moments[1] for ratio in ratios[2:]]
return moments | Compute the distribution's L-moments, e.g. l1, l2, l3, l4, ..
:param args: Distribution parameters in order of shape(s), loc, scale
:type args: float
:param nmom: Number of moments to calculate
:type nmom: int
:param kwds: Distribution parameters as named arguments. See :attr:`rv_continous.shapes` for names of shape
parameters
:type kwds: float
:returns: List of L-moments
:rtype: list | https://github.com/OpenHydrology/lmoments3/blob/65934df58cd754f1a38e35dc5ee6c30717e5b94c/lmoments3/distr.py#L67-L84 |
OpenHydrology/lmoments3 | lmoments3/distr.py | LmomDistrMixin.lmom_ratios | def lmom_ratios(self, *args, nmom=5, **kwds):
"""
Compute the distribution's L-moment ratios, e.g. l1, l2, t3, t4, ..
:param args: Distribution parameters in order of shape(s), loc, scale
:type args: float
:param nmom: Number of moments to calculate
:type nmom: int
:param kwds: Distribution parameters as named arguments. See :attr:`rv_continous.shapes` for names of shape
parameters
:type kwds: float
:returns: List of L-moment ratios
:rtype: list
"""
if nmom > 20:
return ValueError("Parameter nmom too large. Max of 20.")
shapes, loc, scale = self._parse_args(*args, **kwds)
if scale <= 0:
return ValueError("Invalid scale parameter.")
return self._lmom_ratios(*shapes, loc=loc, scale=scale, nmom=nmom) | python | def lmom_ratios(self, *args, nmom=5, **kwds):
"""
Compute the distribution's L-moment ratios, e.g. l1, l2, t3, t4, ..
:param args: Distribution parameters in order of shape(s), loc, scale
:type args: float
:param nmom: Number of moments to calculate
:type nmom: int
:param kwds: Distribution parameters as named arguments. See :attr:`rv_continous.shapes` for names of shape
parameters
:type kwds: float
:returns: List of L-moment ratios
:rtype: list
"""
if nmom > 20:
return ValueError("Parameter nmom too large. Max of 20.")
shapes, loc, scale = self._parse_args(*args, **kwds)
if scale <= 0:
return ValueError("Invalid scale parameter.")
return self._lmom_ratios(*shapes, loc=loc, scale=scale, nmom=nmom) | Compute the distribution's L-moment ratios, e.g. l1, l2, t3, t4, ..
:param args: Distribution parameters in order of shape(s), loc, scale
:type args: float
:param nmom: Number of moments to calculate
:type nmom: int
:param kwds: Distribution parameters as named arguments. See :attr:`rv_continous.shapes` for names of shape
parameters
:type kwds: float
:returns: List of L-moment ratios
:rtype: list | https://github.com/OpenHydrology/lmoments3/blob/65934df58cd754f1a38e35dc5ee6c30717e5b94c/lmoments3/distr.py#L86-L108 |
benjamin-hodgson/Contexts | src/contexts/__init__.py | run | def run():
"""
Run all the test classes in the main module.
Returns: exit code as an integer.
The default behaviour (which may be overridden by plugins) is to return a 0
exit code if the test run succeeded, and 1 if it failed.
"""
plugin_list = load_plugins()
module = sys.modules['__main__']
plugin_list.insert(0, ObjectSupplier(module))
return run_with_plugins(plugin_list) | python | def run():
"""
Run all the test classes in the main module.
Returns: exit code as an integer.
The default behaviour (which may be overridden by plugins) is to return a 0
exit code if the test run succeeded, and 1 if it failed.
"""
plugin_list = load_plugins()
module = sys.modules['__main__']
plugin_list.insert(0, ObjectSupplier(module))
return run_with_plugins(plugin_list) | Run all the test classes in the main module.
Returns: exit code as an integer.
The default behaviour (which may be overridden by plugins) is to return a 0
exit code if the test run succeeded, and 1 if it failed. | https://github.com/benjamin-hodgson/Contexts/blob/f5ee6a08aed19ab157158c1fc7752cff18cceb91/src/contexts/__init__.py#L26-L39 |
benjamin-hodgson/Contexts | src/contexts/__init__.py | run_with_plugins | def run_with_plugins(plugin_list):
"""
Carry out a test run with the supplied list of plugin instances.
The plugins are expected to identify the object to run.
Parameters:
plugin_list: a list of plugin instances (objects which implement some subset of PluginInterface)
Returns: exit code as an integer.
The default behaviour (which may be overridden by plugins) is to return a 0
exit code if the test run succeeded, and 1 if it failed.
"""
composite = core.PluginComposite(plugin_list)
to_run = composite.get_object_to_run()
test_run = core.TestRun(to_run, composite)
test_run.run()
return composite.get_exit_code() | python | def run_with_plugins(plugin_list):
"""
Carry out a test run with the supplied list of plugin instances.
The plugins are expected to identify the object to run.
Parameters:
plugin_list: a list of plugin instances (objects which implement some subset of PluginInterface)
Returns: exit code as an integer.
The default behaviour (which may be overridden by plugins) is to return a 0
exit code if the test run succeeded, and 1 if it failed.
"""
composite = core.PluginComposite(plugin_list)
to_run = composite.get_object_to_run()
test_run = core.TestRun(to_run, composite)
test_run.run()
return composite.get_exit_code() | Carry out a test run with the supplied list of plugin instances.
The plugins are expected to identify the object to run.
Parameters:
plugin_list: a list of plugin instances (objects which implement some subset of PluginInterface)
Returns: exit code as an integer.
The default behaviour (which may be overridden by plugins) is to return a 0
exit code if the test run succeeded, and 1 if it failed. | https://github.com/benjamin-hodgson/Contexts/blob/f5ee6a08aed19ab157158c1fc7752cff18cceb91/src/contexts/__init__.py#L42-L60 |
benjamin-hodgson/Contexts | src/contexts/plugins/identification/filespec.py | FileSpecIdentifier.initialise | def initialise(self, args=None, env=None, file=None, cwd=None):
"""
Filthy hack: we provide file and cwd here rather than as constructor
args because Mr Hodgson decided to pass stdout as the only parameter
to __init__.
File should only be passed during tests.
"""
self.spec_file = args and args.specs or None
self.cwd = cwd or os.getcwd()
self.file = file
return self.spec_file is not None | python | def initialise(self, args=None, env=None, file=None, cwd=None):
"""
Filthy hack: we provide file and cwd here rather than as constructor
args because Mr Hodgson decided to pass stdout as the only parameter
to __init__.
File should only be passed during tests.
"""
self.spec_file = args and args.specs or None
self.cwd = cwd or os.getcwd()
self.file = file
return self.spec_file is not None | Filthy hack: we provide file and cwd here rather than as constructor
args because Mr Hodgson decided to pass stdout as the only parameter
to __init__.
File should only be passed during tests. | https://github.com/benjamin-hodgson/Contexts/blob/f5ee6a08aed19ab157158c1fc7752cff18cceb91/src/contexts/plugins/identification/filespec.py#L19-L29 |
OpenHydrology/lmoments3 | lmoments3/__init__.py | lmom_ratios | def lmom_ratios(data, nmom=5):
"""
Estimate `nmom` number of L-moments from a sample `data`.
:param data: Sequence of (sample) data
:type data: list or array-like sequence
:param nmom: number of L-moments to estimate
:type nmom: int
:return: L-moment ratios like this: l1, l2, t3, t4, t5, .. . As in: items 3 and higher are L-moment ratios.
:rtype: list
"""
if nmom <= 5:
return _samlmusmall(data, nmom)
else:
return _samlmularge(data, nmom) | python | def lmom_ratios(data, nmom=5):
"""
Estimate `nmom` number of L-moments from a sample `data`.
:param data: Sequence of (sample) data
:type data: list or array-like sequence
:param nmom: number of L-moments to estimate
:type nmom: int
:return: L-moment ratios like this: l1, l2, t3, t4, t5, .. . As in: items 3 and higher are L-moment ratios.
:rtype: list
"""
if nmom <= 5:
return _samlmusmall(data, nmom)
else:
return _samlmularge(data, nmom) | Estimate `nmom` number of L-moments from a sample `data`.
:param data: Sequence of (sample) data
:type data: list or array-like sequence
:param nmom: number of L-moments to estimate
:type nmom: int
:return: L-moment ratios like this: l1, l2, t3, t4, t5, .. . As in: items 3 and higher are L-moment ratios.
:rtype: list | https://github.com/OpenHydrology/lmoments3/blob/65934df58cd754f1a38e35dc5ee6c30717e5b94c/lmoments3/__init__.py#L69-L84 |
sporteasy/python-poeditor | poeditor/client.py | POEditorAPI._run | def _run(self, url_path, headers=None, **kwargs):
"""
Requests API
"""
url = self._construct_url(url_path)
payload = kwargs
payload.update({'api_token': self.api_token})
return self._make_request(url, payload, headers) | python | def _run(self, url_path, headers=None, **kwargs):
"""
Requests API
"""
url = self._construct_url(url_path)
payload = kwargs
payload.update({'api_token': self.api_token})
return self._make_request(url, payload, headers) | Requests API | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L129-L138 |
sporteasy/python-poeditor | poeditor/client.py | POEditorAPI._apiv1_run | def _apiv1_run(self, action, headers=None, **kwargs):
"""
Kept for backwards compatibility of this client
See "self.clear_reference_language"
"""
warnings.warn(
"POEditor API v1 is deprecated. Use POEditorAPI._run method to call API v2",
DeprecationWarning, stacklevel=2
)
url = "https://poeditor.com/api/"
payload = kwargs
payload.update({'action': action, 'api_token': self.api_token})
return self._make_request(url, payload, headers) | python | def _apiv1_run(self, action, headers=None, **kwargs):
"""
Kept for backwards compatibility of this client
See "self.clear_reference_language"
"""
warnings.warn(
"POEditor API v1 is deprecated. Use POEditorAPI._run method to call API v2",
DeprecationWarning, stacklevel=2
)
url = "https://poeditor.com/api/"
payload = kwargs
payload.update({'action': action, 'api_token': self.api_token})
return self._make_request(url, payload, headers) | Kept for backwards compatibility of this client
See "self.clear_reference_language" | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L140-L154 |
sporteasy/python-poeditor | poeditor/client.py | POEditorAPI._project_formatter | def _project_formatter(self, data):
"""
Project object
"""
open_ = False if not data['open'] or data['open'] == '0' else True
public = False if not data['public'] or data['public'] == '0' else True
output = {
'created': parse_datetime(data['created']),
'id': int(data['id']),
'name': data['name'],
'open': open_,
'public': public,
}
# the detail view returns more info than the list view
# see https://poeditor.com/docs/api#projects_view
for key in ['description', 'reference_language', 'terms']:
if key in data:
output[key] = data[key]
return output | python | def _project_formatter(self, data):
"""
Project object
"""
open_ = False if not data['open'] or data['open'] == '0' else True
public = False if not data['public'] or data['public'] == '0' else True
output = {
'created': parse_datetime(data['created']),
'id': int(data['id']),
'name': data['name'],
'open': open_,
'public': public,
}
# the detail view returns more info than the list view
# see https://poeditor.com/docs/api#projects_view
for key in ['description', 'reference_language', 'terms']:
if key in data:
output[key] = data[key]
return output | Project object | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L156-L176 |
sporteasy/python-poeditor | poeditor/client.py | POEditorAPI.list_projects | def list_projects(self):
"""
Returns the list of projects owned by user.
"""
data = self._run(
url_path="projects/list"
)
projects = data['result'].get('projects', [])
return [self._project_formatter(item) for item in projects] | python | def list_projects(self):
"""
Returns the list of projects owned by user.
"""
data = self._run(
url_path="projects/list"
)
projects = data['result'].get('projects', [])
return [self._project_formatter(item) for item in projects] | Returns the list of projects owned by user. | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L178-L186 |
sporteasy/python-poeditor | poeditor/client.py | POEditorAPI.create_project | def create_project(self, name, description=None):
"""
creates a new project. Returns the id of the project (if successful)
"""
description = description or ''
data = self._run(
url_path="projects/add",
name=name,
description=description
)
return data['result']['project']['id'] | python | def create_project(self, name, description=None):
"""
creates a new project. Returns the id of the project (if successful)
"""
description = description or ''
data = self._run(
url_path="projects/add",
name=name,
description=description
)
return data['result']['project']['id'] | creates a new project. Returns the id of the project (if successful) | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L188-L198 |
sporteasy/python-poeditor | poeditor/client.py | POEditorAPI.update_project | def update_project(self, project_id, name=None, description=None,
reference_language=None):
"""
Updates project settings (name, description, reference language)
If optional parameters are not sent, their respective fields are not updated.
"""
kwargs = {}
if name is not None:
kwargs['name'] = name
if description is not None:
kwargs['description'] = description
if reference_language is not None:
kwargs['reference_language'] = reference_language
data = self._run(
url_path="projects/update",
id=project_id,
**kwargs
)
return data['result']['project']['id'] | python | def update_project(self, project_id, name=None, description=None,
reference_language=None):
"""
Updates project settings (name, description, reference language)
If optional parameters are not sent, their respective fields are not updated.
"""
kwargs = {}
if name is not None:
kwargs['name'] = name
if description is not None:
kwargs['description'] = description
if reference_language is not None:
kwargs['reference_language'] = reference_language
data = self._run(
url_path="projects/update",
id=project_id,
**kwargs
)
return data['result']['project']['id'] | Updates project settings (name, description, reference language)
If optional parameters are not sent, their respective fields are not updated. | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L200-L219 |
sporteasy/python-poeditor | poeditor/client.py | POEditorAPI.view_project_details | def view_project_details(self, project_id):
"""
Returns project's details.
"""
data = self._run(
url_path="projects/view",
id=project_id
)
return self._project_formatter(data['result']['project']) | python | def view_project_details(self, project_id):
"""
Returns project's details.
"""
data = self._run(
url_path="projects/view",
id=project_id
)
return self._project_formatter(data['result']['project']) | Returns project's details. | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L232-L240 |
sporteasy/python-poeditor | poeditor/client.py | POEditorAPI.list_project_languages | def list_project_languages(self, project_id):
"""
Returns project languages, percentage of translation done for each and the
datetime (UTC - ISO 8601) when the last change was made.
"""
data = self._run(
url_path="languages/list",
id=project_id
)
return data['result'].get('languages', []) | python | def list_project_languages(self, project_id):
"""
Returns project languages, percentage of translation done for each and the
datetime (UTC - ISO 8601) when the last change was made.
"""
data = self._run(
url_path="languages/list",
id=project_id
)
return data['result'].get('languages', []) | Returns project languages, percentage of translation done for each and the
datetime (UTC - ISO 8601) when the last change was made. | https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L242-L251 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.