nwo
stringlengths
6
76
sha
stringlengths
40
40
path
stringlengths
5
118
language
stringclasses
1 value
identifier
stringlengths
1
89
parameters
stringlengths
2
5.4k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
51.1k
docstring
stringlengths
1
17.6k
docstring_summary
stringlengths
0
7.02k
docstring_tokens
sequence
function
stringlengths
30
51.1k
function_tokens
sequence
url
stringlengths
85
218
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/Tooltip.py
python
ToolTip.spawn
( self, event=None )
Spawn the ToolTip. This simply makes the ToolTip eligible for display. Usually this is caused by entering the widget Arguments: event: The event that called this funciton
Spawn the ToolTip. This simply makes the ToolTip eligible for display. Usually this is caused by entering the widget Arguments: event: The event that called this funciton
[ "Spawn", "the", "ToolTip", ".", "This", "simply", "makes", "the", "ToolTip", "eligible", "for", "display", ".", "Usually", "this", "is", "caused", "by", "entering", "the", "widget", "Arguments", ":", "event", ":", "The", "event", "that", "called", "this", "funciton" ]
def spawn( self, event=None ): """ Spawn the ToolTip. This simply makes the ToolTip eligible for display. Usually this is caused by entering the widget Arguments: event: The event that called this funciton """ self.visible = 1 # The after function takes a time argument in miliseconds self.after( int( ToolTip.ShowTipDelay * 1000 ), self.show )
[ "def", "spawn", "(", "self", ",", "event", "=", "None", ")", ":", "self", ".", "visible", "=", "1", "# The after function takes a time argument in miliseconds", "self", ".", "after", "(", "int", "(", "ToolTip", ".", "ShowTipDelay", "*", "1000", ")", ",", "self", ".", "show", ")" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/Tooltip.py#L149-L158
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/Tooltip.py
python
ToolTip.show
( self )
Displays the ToolTip if the time delay has been long enough
Displays the ToolTip if the time delay has been long enough
[ "Displays", "the", "ToolTip", "if", "the", "time", "delay", "has", "been", "long", "enough" ]
def show( self ): """ Displays the ToolTip if the time delay has been long enough """ if ToolTip.ShowToolTips is False: return text = self.msgVar.get() if ToolTip.ShowTipNumber is True and self.TipID is not None: # check if text is not there, if so add it if self.TipNumText not in text: self.msgVar.set(self.TipNumText+text) else: text.replace(self.TipNumText,"") self.msgVar.set(text) if self.visible == 1 and time() - self.lastMotion > ToolTip.ShowTipDelay: self.visible = 2 if self.visible == 2: self.deiconify()
[ "def", "show", "(", "self", ")", ":", "if", "ToolTip", ".", "ShowToolTips", "is", "False", ":", "return", "text", "=", "self", ".", "msgVar", ".", "get", "(", ")", "if", "ToolTip", ".", "ShowTipNumber", "is", "True", "and", "self", ".", "TipID", "is", "not", "None", ":", "# check if text is not there, if so add it", "if", "self", ".", "TipNumText", "not", "in", "text", ":", "self", ".", "msgVar", ".", "set", "(", "self", ".", "TipNumText", "+", "text", ")", "else", ":", "text", ".", "replace", "(", "self", ".", "TipNumText", ",", "\"\"", ")", "self", ".", "msgVar", ".", "set", "(", "text", ")", "if", "self", ".", "visible", "==", "1", "and", "time", "(", ")", "-", "self", ".", "lastMotion", ">", "ToolTip", ".", "ShowTipDelay", ":", "self", ".", "visible", "=", "2", "if", "self", ".", "visible", "==", "2", ":", "self", ".", "deiconify", "(", ")" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/Tooltip.py#L160-L177
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/Tooltip.py
python
ToolTip.move
( self, event )
Processes motion within the widget. Arguments: event: The event that called this function
Processes motion within the widget. Arguments: event: The event that called this function
[ "Processes", "motion", "within", "the", "widget", ".", "Arguments", ":", "event", ":", "The", "event", "that", "called", "this", "function" ]
def move( self, event ): """ Processes motion within the widget. Arguments: event: The event that called this function """ self.lastMotion = time() # If the follow flag is not set, motion within the widget will # make the ToolTip dissapear if self.follow == False: self.withdraw() self.visible = 1 # Offset the ToolTip 10x10 pixels southeast of the pointer self.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) ) # Try to call the message function. Will not change the message # if the message function is None or the message function fails try: self.msgVar.set( self.msgFunc() ) except: pass self.after( int( ToolTip.ShowTipDelay * 1000 ), self.show )
[ "def", "move", "(", "self", ",", "event", ")", ":", "self", ".", "lastMotion", "=", "time", "(", ")", "# If the follow flag is not set, motion within the widget will", "# make the ToolTip dissapear", "if", "self", ".", "follow", "==", "False", ":", "self", ".", "withdraw", "(", ")", "self", ".", "visible", "=", "1", "# Offset the ToolTip 10x10 pixels southeast of the pointer", "self", ".", "geometry", "(", "'+%i+%i'", "%", "(", "event", ".", "x_root", "+", "10", ",", "event", ".", "y_root", "+", "10", ")", ")", "# Try to call the message function. Will not change the message", "# if the message function is None or the message function fails", "try", ":", "self", ".", "msgVar", ".", "set", "(", "self", ".", "msgFunc", "(", ")", ")", "except", ":", "pass", "self", ".", "after", "(", "int", "(", "ToolTip", ".", "ShowTipDelay", "*", "1000", ")", ",", "self", ".", "show", ")" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/Tooltip.py#L179-L197
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/Tooltip.py
python
ToolTip.hide
( self, event=None )
Hides the ToolTip. Usually this is caused by leaving the widget Arguments: event: The event that called this function
Hides the ToolTip. Usually this is caused by leaving the widget Arguments: event: The event that called this function
[ "Hides", "the", "ToolTip", ".", "Usually", "this", "is", "caused", "by", "leaving", "the", "widget", "Arguments", ":", "event", ":", "The", "event", "that", "called", "this", "function" ]
def hide( self, event=None ): """ Hides the ToolTip. Usually this is caused by leaving the widget Arguments: event: The event that called this function """ self.visible = 0 self.withdraw()
[ "def", "hide", "(", "self", ",", "event", "=", "None", ")", ":", "self", ".", "visible", "=", "0", "self", ".", "withdraw", "(", ")" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/Tooltip.py#L199-L206
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/Mapping.py
python
ControlMapping.SetControlMapping
( self )
Can't seem to get a foucs highlight around some of the controls. So I'm using color changes to show focus/tab stops. Also, the Scale does not seem to get focus by clicking on it Need to force focus when the user clicks on it
Can't seem to get a foucs highlight around some of the controls. So I'm using color changes to show focus/tab stops. Also, the Scale does not seem to get focus by clicking on it Need to force focus when the user clicks on it
[ "Can", "t", "seem", "to", "get", "a", "foucs", "highlight", "around", "some", "of", "the", "controls", ".", "So", "I", "m", "using", "color", "changes", "to", "show", "focus", "/", "tab", "stops", ".", "Also", "the", "Scale", "does", "not", "seem", "to", "get", "focus", "by", "clicking", "on", "it", "Need", "to", "force", "focus", "when", "the", "user", "clicks", "on", "it" ]
def SetControlMapping ( self ): #Style().configure('.', font=('Helvetica', 12)) # all Style().configure('RedMessage.TLabel',font=('Arial',10,"italic"),foreground='red') # These dont work since they're overriden by the map later on... ??? Style().configure('Error.TEntry',background='red',foreground='white') Style().configure('OK.TEntry',background='white',foreground='black') Style().configure('DataLabel.TLabel',foreground='blue',font=('Arial',10)) Style().configure('StatusBar.TLabel',background=self.FocusColor,relief=SUNKEN) Style().configure('TMenu',background='white',activeforeground='lightblue') ''' Can't seem to get a foucs highlight around some of the controls. So I'm using color changes to show focus/tab stops. Also, the Scale does not seem to get focus by clicking on it Need to force focus when the user clicks on it ''' Style().map('TPanedwindow', background = [ ('!active','#f0f0ff'), ], ) Style().map('TCombobox', fieldbackground = [ ('focus','!disabled',self.FocusColor), ('!focus','active','!disabled',self.NoFocusMouseOverColor), ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor), #('disabled','lightgray'), # Use foreground ], foreground = [ ('disabled','gray'), ('!disabled', 'black') ], selectbackground = [ ('focus','!disabled',self.FocusColor), ('!focus','active','!disabled',self.NoFocusMouseOverColor), ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor), #('disabled','lightgray'), ], selectforeground = [ ('!focus','black'), ('readonly','black'), ('focus','black'), ('disabled','black'), ('!disabled', 'black') ], ) # close map Style().map('TEntry',# This one is just for 'look and feel' fieldbackground = [ ('focus','!disabled', '!invalid' ,self.FocusColor), ('!focus','active','!disabled','!invalid', self.NoFocusMouseOverColor), ('!focus','!active','!disabled','!invalid',self.NoFocusNoMouseOverColor), ('invalid', '#FF0000') #('disabled','lightgray'), ], foreground = [ ('disabled', '!invalid', 'gray'), ('!disabled', '!invalid', 'black') #('invalid', self.NoFocusNoMouseOverColor) ], #background = [ #('focus','!disabled',self.FocusColor), #('!focus','active','!disabled',self.NoFocusMouseOverColor'), #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor), ##('disabled','lightgray'), #], #selectbackground = [ #('focus','!disabled',self.FocusColor), #('!focus','active','!disabled',self.NoFocusMouseOverColor), #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor). ##('disabled','lightgray'), #], selectforeground = [ ('!focus','black'), ('focus','white'), ], ) # close map #Style().map('TMenubutton',# This one is just for 'look and feel' #fieldbackground = [ #('focus','!disabled',self.FocusColor), #('!focus','active','!disabled',self.NoFocusMouseOverColor), #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor), ##('disabled','lightgray'), #], #foreground = [ #('disabled','gray'), #('!disabled', 'black') #], #background = [ #('focus','!disabled',self.FocusColor), #('!focus','active','!disabled',self.NoFocusMouseOverColor), #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor), ##('disabled','lightgray'), #], #selectbackground = [ #('focus','!disabled',self.FocusColor), #('!focus','active','!disabled',self.NoFocusMouseOverColor), #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor), ##('disabled','lightgray'), #], #selectforeground = [ #('!focus','black'), #('focus','white'), #], #) # close map Style().map("Horizontal.TScale", troughcolor = [ ('focus','!disabled',self.FocusColor), ('!focus','active','!disabled',self.NoFocusMouseOverColor), ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor), ('disabled','lightgray'), ], ) # close map Style().map("Vertical.TScale", troughcolor = [ ('focus','!disabled',self.FocusColor), ('!focus','active','!disabled',self.NoFocusMouseOverColor), ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor), ('disabled','lightgray'), ], ) # close map Style().map("TMenu", background = [ ('focus','!disabled',self.FocusColor), ('!focus','active','!disabled',self.NoFocusMouseOverColor), ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor), ('disabled','lightgray'), ], )
[ "def", "SetControlMapping", "(", "self", ")", ":", "#Style().configure('.', font=('Helvetica', 12)) # all", "Style", "(", ")", ".", "configure", "(", "'RedMessage.TLabel'", ",", "font", "=", "(", "'Arial'", ",", "10", ",", "\"italic\"", ")", ",", "foreground", "=", "'red'", ")", "# These dont work since they're overriden by the map later on... ???", "Style", "(", ")", ".", "configure", "(", "'Error.TEntry'", ",", "background", "=", "'red'", ",", "foreground", "=", "'white'", ")", "Style", "(", ")", ".", "configure", "(", "'OK.TEntry'", ",", "background", "=", "'white'", ",", "foreground", "=", "'black'", ")", "Style", "(", ")", ".", "configure", "(", "'DataLabel.TLabel'", ",", "foreground", "=", "'blue'", ",", "font", "=", "(", "'Arial'", ",", "10", ")", ")", "Style", "(", ")", ".", "configure", "(", "'StatusBar.TLabel'", ",", "background", "=", "self", ".", "FocusColor", ",", "relief", "=", "SUNKEN", ")", "Style", "(", ")", ".", "configure", "(", "'TMenu'", ",", "background", "=", "'white'", ",", "activeforeground", "=", "'lightblue'", ")", "Style", "(", ")", ".", "map", "(", "'TPanedwindow'", ",", "background", "=", "[", "(", "'!active'", ",", "'#f0f0ff'", ")", ",", "]", ",", ")", "Style", "(", ")", ".", "map", "(", "'TCombobox'", ",", "fieldbackground", "=", "[", "(", "'focus'", ",", "'!disabled'", ",", "self", ".", "FocusColor", ")", ",", "(", "'!focus'", ",", "'active'", ",", "'!disabled'", ",", "self", ".", "NoFocusMouseOverColor", ")", ",", "(", "'!focus'", ",", "'!active'", ",", "'!disabled'", ",", "self", ".", "NoFocusNoMouseOverColor", ")", ",", "#('disabled','lightgray'), # Use foreground", "]", ",", "foreground", "=", "[", "(", "'disabled'", ",", "'gray'", ")", ",", "(", "'!disabled'", ",", "'black'", ")", "]", ",", "selectbackground", "=", "[", "(", "'focus'", ",", "'!disabled'", ",", "self", ".", "FocusColor", ")", ",", "(", "'!focus'", ",", "'active'", ",", "'!disabled'", ",", "self", ".", "NoFocusMouseOverColor", ")", ",", "(", "'!focus'", ",", "'!active'", ",", "'!disabled'", ",", "self", ".", "NoFocusNoMouseOverColor", ")", ",", "#('disabled','lightgray'),", "]", ",", "selectforeground", "=", "[", "(", "'!focus'", ",", "'black'", ")", ",", "(", "'readonly'", ",", "'black'", ")", ",", "(", "'focus'", ",", "'black'", ")", ",", "(", "'disabled'", ",", "'black'", ")", ",", "(", "'!disabled'", ",", "'black'", ")", "]", ",", ")", "# close map", "Style", "(", ")", ".", "map", "(", "'TEntry'", ",", "# This one is just for 'look and feel'", "fieldbackground", "=", "[", "(", "'focus'", ",", "'!disabled'", ",", "'!invalid'", ",", "self", ".", "FocusColor", ")", ",", "(", "'!focus'", ",", "'active'", ",", "'!disabled'", ",", "'!invalid'", ",", "self", ".", "NoFocusMouseOverColor", ")", ",", "(", "'!focus'", ",", "'!active'", ",", "'!disabled'", ",", "'!invalid'", ",", "self", ".", "NoFocusNoMouseOverColor", ")", ",", "(", "'invalid'", ",", "'#FF0000'", ")", "#('disabled','lightgray'),", "]", ",", "foreground", "=", "[", "(", "'disabled'", ",", "'!invalid'", ",", "'gray'", ")", ",", "(", "'!disabled'", ",", "'!invalid'", ",", "'black'", ")", "#('invalid', self.NoFocusNoMouseOverColor)", "]", ",", "#background = [", "#('focus','!disabled',self.FocusColor),", "#('!focus','active','!disabled',self.NoFocusMouseOverColor'),", "#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),", "##('disabled','lightgray'),", "#],", "#selectbackground = [", "#('focus','!disabled',self.FocusColor),", "#('!focus','active','!disabled',self.NoFocusMouseOverColor),", "#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor).", "##('disabled','lightgray'),", "#],", "selectforeground", "=", "[", "(", "'!focus'", ",", "'black'", ")", ",", "(", "'focus'", ",", "'white'", ")", ",", "]", ",", ")", "# close map", "#Style().map('TMenubutton',# This one is just for 'look and feel'", "#fieldbackground = [", "#('focus','!disabled',self.FocusColor),", "#('!focus','active','!disabled',self.NoFocusMouseOverColor),", "#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),", "##('disabled','lightgray'),", "#],", "#foreground = [", "#('disabled','gray'),", "#('!disabled', 'black')", "#],", "#background = [", "#('focus','!disabled',self.FocusColor),", "#('!focus','active','!disabled',self.NoFocusMouseOverColor),", "#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),", "##('disabled','lightgray'),", "#],", "#selectbackground = [", "#('focus','!disabled',self.FocusColor),", "#('!focus','active','!disabled',self.NoFocusMouseOverColor),", "#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),", "##('disabled','lightgray'),", "#],", "#selectforeground = [", "#('!focus','black'),", "#('focus','white'),", "#],", "#) # close map", "Style", "(", ")", ".", "map", "(", "\"Horizontal.TScale\"", ",", "troughcolor", "=", "[", "(", "'focus'", ",", "'!disabled'", ",", "self", ".", "FocusColor", ")", ",", "(", "'!focus'", ",", "'active'", ",", "'!disabled'", ",", "self", ".", "NoFocusMouseOverColor", ")", ",", "(", "'!focus'", ",", "'!active'", ",", "'!disabled'", ",", "self", ".", "NoFocusNoMouseOverColor", ")", ",", "(", "'disabled'", ",", "'lightgray'", ")", ",", "]", ",", ")", "# close map", "Style", "(", ")", ".", "map", "(", "\"Vertical.TScale\"", ",", "troughcolor", "=", "[", "(", "'focus'", ",", "'!disabled'", ",", "self", ".", "FocusColor", ")", ",", "(", "'!focus'", ",", "'active'", ",", "'!disabled'", ",", "self", ".", "NoFocusMouseOverColor", ")", ",", "(", "'!focus'", ",", "'!active'", ",", "'!disabled'", ",", "self", ".", "NoFocusNoMouseOverColor", ")", ",", "(", "'disabled'", ",", "'lightgray'", ")", ",", "]", ",", ")", "# close map", "Style", "(", ")", ".", "map", "(", "\"TMenu\"", ",", "background", "=", "[", "(", "'focus'", ",", "'!disabled'", ",", "self", ".", "FocusColor", ")", ",", "(", "'!focus'", ",", "'active'", ",", "'!disabled'", ",", "self", ".", "NoFocusMouseOverColor", ")", ",", "(", "'!focus'", ",", "'!active'", ",", "'!disabled'", ",", "self", ".", "NoFocusNoMouseOverColor", ")", ",", "(", "'disabled'", ",", "'lightgray'", ")", ",", "]", ",", ")" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/Mapping.py#L52-L183
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/PiCameraApp.py
python
PiCameraApp.LoadImageFromStream
( self, zoom )
Implement Record Sequence
Implement Record Sequence
[ "Implement", "Record", "Sequence" ]
def LoadImageFromStream ( self, zoom ): if self.photo: del self.photo self.pictureStream.seek(0) self.CurrentImage = PIL.Image.open(self.pictureStream) # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#the-image-class self.RawEXIFData = None if PreferencesDialog.DefaultPhotoFormat == 'jpeg': self.RawEXIFData = self.CurrentImage.info['exif'] # Works!!!! #print ( self.RawEXIFData ) self.CameraUtils.AddEXIFTags(self.CurrentImage) self.ShowHideImageAttributesPane(self.viewImageAttributesPane.get()) # resize what's displayed if user used Ctrl+mousewheel size = self.CurrentImage.size if size[0] <= 1024 and size[1] <= 768: # hold max zoom level width = int(zoom*size[0]) height = int(zoom*size[1]) if width <= 1024 and height <= 768: self.CurrentImage = self.CurrentImage.resize((width,height),PIL.Image.ANTIALIAS) self.CurrentImageSize = self.CurrentImage.size # Convert to canvas compatible format and store on canvas self.photo = ImageTk.PhotoImage(self.CurrentImage) self.photoCanvas.delete("pic") self.photoCanvas.create_image(0,0,image=self.photo,anchor='nw',tags=('pic')) self.photoCanvas.config(scrollregion=self.photoCanvas.bbox(ALL)) self.photoCanvas.tag_raise("objs") # raise Z order of cursors to topmost ''' Implement Record Sequence '''
[ "def", "LoadImageFromStream", "(", "self", ",", "zoom", ")", ":", "if", "self", ".", "photo", ":", "del", "self", ".", "photo", "self", ".", "pictureStream", ".", "seek", "(", "0", ")", "self", ".", "CurrentImage", "=", "PIL", ".", "Image", ".", "open", "(", "self", ".", "pictureStream", ")", "# https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#the-image-class", "self", ".", "RawEXIFData", "=", "None", "if", "PreferencesDialog", ".", "DefaultPhotoFormat", "==", "'jpeg'", ":", "self", ".", "RawEXIFData", "=", "self", ".", "CurrentImage", ".", "info", "[", "'exif'", "]", "# Works!!!!", "#print ( self.RawEXIFData )", "self", ".", "CameraUtils", ".", "AddEXIFTags", "(", "self", ".", "CurrentImage", ")", "self", ".", "ShowHideImageAttributesPane", "(", "self", ".", "viewImageAttributesPane", ".", "get", "(", ")", ")", "# resize what's displayed if user used Ctrl+mousewheel", "size", "=", "self", ".", "CurrentImage", ".", "size", "if", "size", "[", "0", "]", "<=", "1024", "and", "size", "[", "1", "]", "<=", "768", ":", "# hold max zoom level", "width", "=", "int", "(", "zoom", "*", "size", "[", "0", "]", ")", "height", "=", "int", "(", "zoom", "*", "size", "[", "1", "]", ")", "if", "width", "<=", "1024", "and", "height", "<=", "768", ":", "self", ".", "CurrentImage", "=", "self", ".", "CurrentImage", ".", "resize", "(", "(", "width", ",", "height", ")", ",", "PIL", ".", "Image", ".", "ANTIALIAS", ")", "self", ".", "CurrentImageSize", "=", "self", ".", "CurrentImage", ".", "size", "# Convert to canvas compatible format and store on canvas", "self", ".", "photo", "=", "ImageTk", ".", "PhotoImage", "(", "self", ".", "CurrentImage", ")", "self", ".", "photoCanvas", ".", "delete", "(", "\"pic\"", ")", "self", ".", "photoCanvas", ".", "create_image", "(", "0", ",", "0", ",", "image", "=", "self", ".", "photo", ",", "anchor", "=", "'nw'", ",", "tags", "=", "(", "'pic'", ")", ")", "self", ".", "photoCanvas", ".", "config", "(", "scrollregion", "=", "self", ".", "photoCanvas", ".", "bbox", "(", "ALL", ")", ")", "self", ".", "photoCanvas", ".", "tag_raise", "(", "\"objs\"", ")", "# raise Z order of cursors to topmost" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/PiCameraApp.py#L755-L785
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/PiCameraApp.py
python
PiCameraApp.LoseFocus
( self, event )
The Combobox is a problem. Could save last two entries... if Combobox, Labelframe, Tk... NO! this could be the Topwindow losing focus while the Combobox has the focus. The same effect Also, the nesting may vary based on where the Combobox is in the hierarcy. What I really want is to capture the <B1-Motion> on the TopWindow titlebar - OR - get the widget ID to the Combobox Toplevel dropdown window.
The Combobox is a problem. Could save last two entries... if Combobox, Labelframe, Tk... NO! this could be the Topwindow losing focus while the Combobox has the focus. The same effect Also, the nesting may vary based on where the Combobox is in the hierarcy. What I really want is to capture the <B1-Motion> on the TopWindow titlebar - OR - get the widget ID to the Combobox Toplevel dropdown window.
[ "The", "Combobox", "is", "a", "problem", ".", "Could", "save", "last", "two", "entries", "...", "if", "Combobox", "Labelframe", "Tk", "...", "NO!", "this", "could", "be", "the", "Topwindow", "losing", "focus", "while", "the", "Combobox", "has", "the", "focus", ".", "The", "same", "effect", "Also", "the", "nesting", "may", "vary", "based", "on", "where", "the", "Combobox", "is", "in", "the", "hierarcy", ".", "What", "I", "really", "want", "is", "to", "capture", "the", "<B1", "-", "Motion", ">", "on", "the", "TopWindow", "titlebar", "-", "OR", "-", "get", "the", "widget", "ID", "to", "the", "Combobox", "Toplevel", "dropdown", "window", "." ]
def LoseFocus ( self, event ): ''' The Combobox is a problem. Could save last two entries... if Combobox, Labelframe, Tk... NO! this could be the Topwindow losing focus while the Combobox has the focus. The same effect Also, the nesting may vary based on where the Combobox is in the hierarcy. What I really want is to capture the <B1-Motion> on the TopWindow titlebar - OR - get the widget ID to the Combobox Toplevel dropdown window. ''' if self.camera.preview and not self.AlwaysPreview and \ event.widget.winfo_class().lower() == 'tk' and \ self.root.attributes("-topmost") == 0: # TopMost window hack if self.ShowOnScreen.get() == False: self.camera.preview.alpha = 0 self.ImageCanvas.itemconfigure('nopreview',state='normal')
[ "def", "LoseFocus", "(", "self", ",", "event", ")", ":", "if", "self", ".", "camera", ".", "preview", "and", "not", "self", ".", "AlwaysPreview", "and", "event", ".", "widget", ".", "winfo_class", "(", ")", ".", "lower", "(", ")", "==", "'tk'", "and", "self", ".", "root", ".", "attributes", "(", "\"-topmost\"", ")", "==", "0", ":", "# TopMost window hack", "if", "self", ".", "ShowOnScreen", ".", "get", "(", ")", "==", "False", ":", "self", ".", "camera", ".", "preview", ".", "alpha", "=", "0", "self", ".", "ImageCanvas", ".", "itemconfigure", "(", "'nopreview'", ",", "state", "=", "'normal'", ")" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/PiCameraApp.py#L967-L983
Billwilliams1952/PiCameraApp
61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0
Source/PreferencesDialog.py
python
General.BuildPage
( self )
Configuration files in python There are several ways to do this depending on the file format required. ConfigParser [.ini format] Write a file like so: from ConfigParser import SafeConfigParser config = SafeConfigParser() config.read('config.ini') config.add_section('main') config.set('main', 'key1', 'value1') config.set('main', 'key2', 'value2') config.set('main', 'key3', 'value3')
Configuration files in python There are several ways to do this depending on the file format required. ConfigParser [.ini format] Write a file like so: from ConfigParser import SafeConfigParser config = SafeConfigParser() config.read('config.ini') config.add_section('main') config.set('main', 'key1', 'value1') config.set('main', 'key2', 'value2') config.set('main', 'key3', 'value3')
[ "Configuration", "files", "in", "python", "There", "are", "several", "ways", "to", "do", "this", "depending", "on", "the", "file", "format", "required", ".", "ConfigParser", "[", ".", "ini", "format", "]", "Write", "a", "file", "like", "so", ":", "from", "ConfigParser", "import", "SafeConfigParser", "config", "=", "SafeConfigParser", "()", "config", ".", "read", "(", "config", ".", "ini", ")", "config", ".", "add_section", "(", "main", ")", "config", ".", "set", "(", "main", "key1", "value1", ")", "config", ".", "set", "(", "main", "key2", "value2", ")", "config", ".", "set", "(", "main", "key3", "value3", ")" ]
def BuildPage ( self ): # Setup default folder to save pictures and videos f = MyLabelFrame(self,'Set default directories',0,0) self.iconCameraBig = PIL.Image.open('Assets/camera-icon.png') self.iconCameraBig = ImageTk.PhotoImage(self.iconCameraBig.resize((22,22),Image.ANTIALIAS)) self.iconVideoBig = PIL.Image.open('Assets/video-icon-b.png') self.iconVideoBig = ImageTk.PhotoImage(self.iconVideoBig.resize((22,22),Image.ANTIALIAS)) self.iconFiles = PIL.Image.open('Assets/files.png') self.iconFiles = ImageTk.PhotoImage(self.iconFiles.resize((22,22),Image.ANTIALIAS)) b = ttk.Button(f,text="Photos...",image=self.iconCameraBig,compound='left', command=self.SelectPhotoDirectory,width=7) b.grid(row=0,column=0,sticky='W',pady=(5,5)) ToolTip(b,6000) self.PhotoDirLabel = Label(f,foreground='#0000FF', text=PreferencesDialog.DefaultPhotoDir,anchor=W) self.PhotoDirLabel.grid(row=0,column=1,sticky='EW',padx=10); ToolTip(self.PhotoDirLabel,6001) b = ttk.Button(f,text="Videos...",image=self.iconVideoBig,compound='left', command=self.SelectVideoDirectory,width=7) b.grid(row=1,column=0,sticky='W') ToolTip(b,6002) self.VideoDirLabel = Label(f,foreground='#0000FF', text=PreferencesDialog.DefaultVideoDir,anchor=W) self.VideoDirLabel.grid(row=1,column=1,sticky='EW',padx=10); ToolTip(self.VideoDirLabel,6003) b = ttk.Button(f,text="Files...",image=self.iconFiles,compound='left', command=self.SelectFilesDirectory,width=7) b.grid(row=2,column=0,sticky='W',pady=(5,5)) ToolTip(b,6004) self.FilesDirLabel = Label(f,foreground='#0000FF', text=PreferencesDialog.DefaultFilesDir,anchor=W) self.FilesDirLabel.grid(row=2,column=1,sticky='EW',padx=10); ToolTip(self.FilesDirLabel,6005) f = MyLabelFrame(self,'Photo/Video capture formats',1,0) ttk.Label(f,text='Photo capture format',padding=(5,5,5,5)) \ .grid(row=0,column=0,sticky='W') self.photoCaptureFormatCombo = Combobox(f,height=15,width=8, state='readonly')#,width=15) self.photoCaptureFormatCombo.grid(row=0,column=1,sticky='EW') self.photoFormats = ['jpeg','png','bmp', 'gif','yuv','rgb','rgba','bgr','bgra','raw'] self.photoCaptureFormatCombo['values'] = self.photoFormats self.photoCaptureFormatCombo.current( \ self.photoFormats.index(PreferencesDialog.DefaultPhotoFormat)) self.photoCaptureFormatCombo.bind('<<ComboboxSelected>>', self.photoCaptureFormatChanged) ToolTip(self.photoCaptureFormatCombo, msg=6010) self.ModFormatParams = ttk.Button(f,text='Params...', command=self.ModifyFormatParamPressed, underline=0,padding=(5,3,5,3),width=8) self.ModFormatParams.grid(row=0,column=2,sticky='W',padx=5) ToolTip(self.ModFormatParams, msg=6011) ttk.Label(f,text='Video capture format',padding=(5,5,5,5)) \ .grid(row=1,column=0,sticky='W') self.VideoCaptureFormatCombo = Combobox(f,height=15,width=8, state='readonly')#,width=15) self.VideoCaptureFormatCombo.grid(row=1,column=1,sticky='EW') self.videoFormats = ['h264','mjpeg','yuv', 'rgb','rgba','bgr','bgra'] self.VideoCaptureFormatCombo['values'] = self.videoFormats self.VideoCaptureFormatCombo.current( \ self.videoFormats.index(PreferencesDialog.DefaultVideoFormat)) self.VideoCaptureFormatCombo.bind('<<ComboboxSelected>>', self.VideoCaptureFormatChanged) ToolTip(self.VideoCaptureFormatCombo,6020) self.ModVideoFormatParams = ttk.Button(f,text='Params...', command=self.ModifyVideoFormatParamPressed, underline=0,padding=(5,3,5,3),width=8) self.ModVideoFormatParams.grid(row=1,column=2,sticky='W',padx=5) ToolTip(self.ModVideoFormatParams,6021) # Save / Restore camera settings? This may be a bit to do f = MyLabelFrame(self,'Photo/Video naming',2,0) Label(f,text='Timestamp format:') \ .grid(row=0,column=0,sticky='W') okCmd = (self.register(self.ValidateTimestamp),'%P') self.TimeStamp = MyStringVar(PreferencesDialog.DefaultTimestampFormat) e = Entry(f,width=20,validate='all', textvariable=self.TimeStamp) e.grid(row=0,column=1,sticky='W') ToolTip(e,6050) image = PIL.Image.open('Assets/help.png') self.helpimage = ImageTk.PhotoImage(image.resize((16,16))) b = ttk.Button(f,image=self.helpimage,width=10, command=self.FormatHelp,padding=(2,2,2,2)) b.grid(row=0,column=2,padx=5) ToolTip(b,6052) Label(f,text='Sample timestamp:').grid(row=1,column=0,sticky='W') self.TimestampLabel = MyStringVar(datetime.datetime.now() \ .strftime(PreferencesDialog.DefaultTimestampFormat)) self.tsl = Label(f,textvariable=self.TimestampLabel,foreground='#0000FF') self.tsl.grid(row=1,column=1,columnspan=2,sticky='W') ToolTip(self.tsl,6051) self.after(1000,self.UpdateTimestamp) self.PhotoTimestampVar = MyBooleanVar(PreferencesDialog.PhotoTimestamp) self.PhotoTimestamp = Checkbutton(f,text='Include timestamp in photo name', variable=self.PhotoTimestampVar, command=self.PhotoTimestampChecked) self.PhotoTimestamp.grid(row=2,column=0,columnspan=2,sticky='W') ToolTip(self.PhotoTimestamp,6060) self.VideoTimestampVar = MyBooleanVar(PreferencesDialog.VideoTimestamp) self.VideoTimestamp = Checkbutton(f,text='Include timestamp in video name', variable=self.VideoTimestampVar, command=self.VideoTimestampChecked) self.VideoTimestamp.grid(row=3,column=0,columnspan=2,sticky='W') ToolTip(self.VideoTimestamp,6061) e.config(validatecommand=okCmd) ''' Configuration files in python There are several ways to do this depending on the file format required. ConfigParser [.ini format] Write a file like so: from ConfigParser import SafeConfigParser config = SafeConfigParser() config.read('config.ini') config.add_section('main') config.set('main', 'key1', 'value1') config.set('main', 'key2', 'value2') config.set('main', 'key3', 'value3') ''' self.photoCaptureFormatChanged(None) self.VideoCaptureFormatChanged(None)
[ "def", "BuildPage", "(", "self", ")", ":", "# Setup default folder to save pictures and videos", "f", "=", "MyLabelFrame", "(", "self", ",", "'Set default directories'", ",", "0", ",", "0", ")", "self", ".", "iconCameraBig", "=", "PIL", ".", "Image", ".", "open", "(", "'Assets/camera-icon.png'", ")", "self", ".", "iconCameraBig", "=", "ImageTk", ".", "PhotoImage", "(", "self", ".", "iconCameraBig", ".", "resize", "(", "(", "22", ",", "22", ")", ",", "Image", ".", "ANTIALIAS", ")", ")", "self", ".", "iconVideoBig", "=", "PIL", ".", "Image", ".", "open", "(", "'Assets/video-icon-b.png'", ")", "self", ".", "iconVideoBig", "=", "ImageTk", ".", "PhotoImage", "(", "self", ".", "iconVideoBig", ".", "resize", "(", "(", "22", ",", "22", ")", ",", "Image", ".", "ANTIALIAS", ")", ")", "self", ".", "iconFiles", "=", "PIL", ".", "Image", ".", "open", "(", "'Assets/files.png'", ")", "self", ".", "iconFiles", "=", "ImageTk", ".", "PhotoImage", "(", "self", ".", "iconFiles", ".", "resize", "(", "(", "22", ",", "22", ")", ",", "Image", ".", "ANTIALIAS", ")", ")", "b", "=", "ttk", ".", "Button", "(", "f", ",", "text", "=", "\"Photos...\"", ",", "image", "=", "self", ".", "iconCameraBig", ",", "compound", "=", "'left'", ",", "command", "=", "self", ".", "SelectPhotoDirectory", ",", "width", "=", "7", ")", "b", ".", "grid", "(", "row", "=", "0", ",", "column", "=", "0", ",", "sticky", "=", "'W'", ",", "pady", "=", "(", "5", ",", "5", ")", ")", "ToolTip", "(", "b", ",", "6000", ")", "self", ".", "PhotoDirLabel", "=", "Label", "(", "f", ",", "foreground", "=", "'#0000FF'", ",", "text", "=", "PreferencesDialog", ".", "DefaultPhotoDir", ",", "anchor", "=", "W", ")", "self", ".", "PhotoDirLabel", ".", "grid", "(", "row", "=", "0", ",", "column", "=", "1", ",", "sticky", "=", "'EW'", ",", "padx", "=", "10", ")", "ToolTip", "(", "self", ".", "PhotoDirLabel", ",", "6001", ")", "b", "=", "ttk", ".", "Button", "(", "f", ",", "text", "=", "\"Videos...\"", ",", "image", "=", "self", ".", "iconVideoBig", ",", "compound", "=", "'left'", ",", "command", "=", "self", ".", "SelectVideoDirectory", ",", "width", "=", "7", ")", "b", ".", "grid", "(", "row", "=", "1", ",", "column", "=", "0", ",", "sticky", "=", "'W'", ")", "ToolTip", "(", "b", ",", "6002", ")", "self", ".", "VideoDirLabel", "=", "Label", "(", "f", ",", "foreground", "=", "'#0000FF'", ",", "text", "=", "PreferencesDialog", ".", "DefaultVideoDir", ",", "anchor", "=", "W", ")", "self", ".", "VideoDirLabel", ".", "grid", "(", "row", "=", "1", ",", "column", "=", "1", ",", "sticky", "=", "'EW'", ",", "padx", "=", "10", ")", "ToolTip", "(", "self", ".", "VideoDirLabel", ",", "6003", ")", "b", "=", "ttk", ".", "Button", "(", "f", ",", "text", "=", "\"Files...\"", ",", "image", "=", "self", ".", "iconFiles", ",", "compound", "=", "'left'", ",", "command", "=", "self", ".", "SelectFilesDirectory", ",", "width", "=", "7", ")", "b", ".", "grid", "(", "row", "=", "2", ",", "column", "=", "0", ",", "sticky", "=", "'W'", ",", "pady", "=", "(", "5", ",", "5", ")", ")", "ToolTip", "(", "b", ",", "6004", ")", "self", ".", "FilesDirLabel", "=", "Label", "(", "f", ",", "foreground", "=", "'#0000FF'", ",", "text", "=", "PreferencesDialog", ".", "DefaultFilesDir", ",", "anchor", "=", "W", ")", "self", ".", "FilesDirLabel", ".", "grid", "(", "row", "=", "2", ",", "column", "=", "1", ",", "sticky", "=", "'EW'", ",", "padx", "=", "10", ")", "ToolTip", "(", "self", ".", "FilesDirLabel", ",", "6005", ")", "f", "=", "MyLabelFrame", "(", "self", ",", "'Photo/Video capture formats'", ",", "1", ",", "0", ")", "ttk", ".", "Label", "(", "f", ",", "text", "=", "'Photo capture format'", ",", "padding", "=", "(", "5", ",", "5", ",", "5", ",", "5", ")", ")", ".", "grid", "(", "row", "=", "0", ",", "column", "=", "0", ",", "sticky", "=", "'W'", ")", "self", ".", "photoCaptureFormatCombo", "=", "Combobox", "(", "f", ",", "height", "=", "15", ",", "width", "=", "8", ",", "state", "=", "'readonly'", ")", "#,width=15)", "self", ".", "photoCaptureFormatCombo", ".", "grid", "(", "row", "=", "0", ",", "column", "=", "1", ",", "sticky", "=", "'EW'", ")", "self", ".", "photoFormats", "=", "[", "'jpeg'", ",", "'png'", ",", "'bmp'", ",", "'gif'", ",", "'yuv'", ",", "'rgb'", ",", "'rgba'", ",", "'bgr'", ",", "'bgra'", ",", "'raw'", "]", "self", ".", "photoCaptureFormatCombo", "[", "'values'", "]", "=", "self", ".", "photoFormats", "self", ".", "photoCaptureFormatCombo", ".", "current", "(", "self", ".", "photoFormats", ".", "index", "(", "PreferencesDialog", ".", "DefaultPhotoFormat", ")", ")", "self", ".", "photoCaptureFormatCombo", ".", "bind", "(", "'<<ComboboxSelected>>'", ",", "self", ".", "photoCaptureFormatChanged", ")", "ToolTip", "(", "self", ".", "photoCaptureFormatCombo", ",", "msg", "=", "6010", ")", "self", ".", "ModFormatParams", "=", "ttk", ".", "Button", "(", "f", ",", "text", "=", "'Params...'", ",", "command", "=", "self", ".", "ModifyFormatParamPressed", ",", "underline", "=", "0", ",", "padding", "=", "(", "5", ",", "3", ",", "5", ",", "3", ")", ",", "width", "=", "8", ")", "self", ".", "ModFormatParams", ".", "grid", "(", "row", "=", "0", ",", "column", "=", "2", ",", "sticky", "=", "'W'", ",", "padx", "=", "5", ")", "ToolTip", "(", "self", ".", "ModFormatParams", ",", "msg", "=", "6011", ")", "ttk", ".", "Label", "(", "f", ",", "text", "=", "'Video capture format'", ",", "padding", "=", "(", "5", ",", "5", ",", "5", ",", "5", ")", ")", ".", "grid", "(", "row", "=", "1", ",", "column", "=", "0", ",", "sticky", "=", "'W'", ")", "self", ".", "VideoCaptureFormatCombo", "=", "Combobox", "(", "f", ",", "height", "=", "15", ",", "width", "=", "8", ",", "state", "=", "'readonly'", ")", "#,width=15)", "self", ".", "VideoCaptureFormatCombo", ".", "grid", "(", "row", "=", "1", ",", "column", "=", "1", ",", "sticky", "=", "'EW'", ")", "self", ".", "videoFormats", "=", "[", "'h264'", ",", "'mjpeg'", ",", "'yuv'", ",", "'rgb'", ",", "'rgba'", ",", "'bgr'", ",", "'bgra'", "]", "self", ".", "VideoCaptureFormatCombo", "[", "'values'", "]", "=", "self", ".", "videoFormats", "self", ".", "VideoCaptureFormatCombo", ".", "current", "(", "self", ".", "videoFormats", ".", "index", "(", "PreferencesDialog", ".", "DefaultVideoFormat", ")", ")", "self", ".", "VideoCaptureFormatCombo", ".", "bind", "(", "'<<ComboboxSelected>>'", ",", "self", ".", "VideoCaptureFormatChanged", ")", "ToolTip", "(", "self", ".", "VideoCaptureFormatCombo", ",", "6020", ")", "self", ".", "ModVideoFormatParams", "=", "ttk", ".", "Button", "(", "f", ",", "text", "=", "'Params...'", ",", "command", "=", "self", ".", "ModifyVideoFormatParamPressed", ",", "underline", "=", "0", ",", "padding", "=", "(", "5", ",", "3", ",", "5", ",", "3", ")", ",", "width", "=", "8", ")", "self", ".", "ModVideoFormatParams", ".", "grid", "(", "row", "=", "1", ",", "column", "=", "2", ",", "sticky", "=", "'W'", ",", "padx", "=", "5", ")", "ToolTip", "(", "self", ".", "ModVideoFormatParams", ",", "6021", ")", "# Save / Restore camera settings? This may be a bit to do", "f", "=", "MyLabelFrame", "(", "self", ",", "'Photo/Video naming'", ",", "2", ",", "0", ")", "Label", "(", "f", ",", "text", "=", "'Timestamp format:'", ")", ".", "grid", "(", "row", "=", "0", ",", "column", "=", "0", ",", "sticky", "=", "'W'", ")", "okCmd", "=", "(", "self", ".", "register", "(", "self", ".", "ValidateTimestamp", ")", ",", "'%P'", ")", "self", ".", "TimeStamp", "=", "MyStringVar", "(", "PreferencesDialog", ".", "DefaultTimestampFormat", ")", "e", "=", "Entry", "(", "f", ",", "width", "=", "20", ",", "validate", "=", "'all'", ",", "textvariable", "=", "self", ".", "TimeStamp", ")", "e", ".", "grid", "(", "row", "=", "0", ",", "column", "=", "1", ",", "sticky", "=", "'W'", ")", "ToolTip", "(", "e", ",", "6050", ")", "image", "=", "PIL", ".", "Image", ".", "open", "(", "'Assets/help.png'", ")", "self", ".", "helpimage", "=", "ImageTk", ".", "PhotoImage", "(", "image", ".", "resize", "(", "(", "16", ",", "16", ")", ")", ")", "b", "=", "ttk", ".", "Button", "(", "f", ",", "image", "=", "self", ".", "helpimage", ",", "width", "=", "10", ",", "command", "=", "self", ".", "FormatHelp", ",", "padding", "=", "(", "2", ",", "2", ",", "2", ",", "2", ")", ")", "b", ".", "grid", "(", "row", "=", "0", ",", "column", "=", "2", ",", "padx", "=", "5", ")", "ToolTip", "(", "b", ",", "6052", ")", "Label", "(", "f", ",", "text", "=", "'Sample timestamp:'", ")", ".", "grid", "(", "row", "=", "1", ",", "column", "=", "0", ",", "sticky", "=", "'W'", ")", "self", ".", "TimestampLabel", "=", "MyStringVar", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "PreferencesDialog", ".", "DefaultTimestampFormat", ")", ")", "self", ".", "tsl", "=", "Label", "(", "f", ",", "textvariable", "=", "self", ".", "TimestampLabel", ",", "foreground", "=", "'#0000FF'", ")", "self", ".", "tsl", ".", "grid", "(", "row", "=", "1", ",", "column", "=", "1", ",", "columnspan", "=", "2", ",", "sticky", "=", "'W'", ")", "ToolTip", "(", "self", ".", "tsl", ",", "6051", ")", "self", ".", "after", "(", "1000", ",", "self", ".", "UpdateTimestamp", ")", "self", ".", "PhotoTimestampVar", "=", "MyBooleanVar", "(", "PreferencesDialog", ".", "PhotoTimestamp", ")", "self", ".", "PhotoTimestamp", "=", "Checkbutton", "(", "f", ",", "text", "=", "'Include timestamp in photo name'", ",", "variable", "=", "self", ".", "PhotoTimestampVar", ",", "command", "=", "self", ".", "PhotoTimestampChecked", ")", "self", ".", "PhotoTimestamp", ".", "grid", "(", "row", "=", "2", ",", "column", "=", "0", ",", "columnspan", "=", "2", ",", "sticky", "=", "'W'", ")", "ToolTip", "(", "self", ".", "PhotoTimestamp", ",", "6060", ")", "self", ".", "VideoTimestampVar", "=", "MyBooleanVar", "(", "PreferencesDialog", ".", "VideoTimestamp", ")", "self", ".", "VideoTimestamp", "=", "Checkbutton", "(", "f", ",", "text", "=", "'Include timestamp in video name'", ",", "variable", "=", "self", ".", "VideoTimestampVar", ",", "command", "=", "self", ".", "VideoTimestampChecked", ")", "self", ".", "VideoTimestamp", ".", "grid", "(", "row", "=", "3", ",", "column", "=", "0", ",", "columnspan", "=", "2", ",", "sticky", "=", "'W'", ")", "ToolTip", "(", "self", ".", "VideoTimestamp", ",", "6061", ")", "e", ".", "config", "(", "validatecommand", "=", "okCmd", ")", "self", ".", "photoCaptureFormatChanged", "(", "None", ")", "self", ".", "VideoCaptureFormatChanged", "(", "None", ")" ]
https://github.com/Billwilliams1952/PiCameraApp/blob/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0/Source/PreferencesDialog.py#L111-L242
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
rickmote.py
python
matching_line
(lines, keyword)
return None
Returns the first matching line in a list of lines. See match()
Returns the first matching line in a list of lines. See match()
[ "Returns", "the", "first", "matching", "line", "in", "a", "list", "of", "lines", ".", "See", "match", "()" ]
def matching_line(lines, keyword): """Returns the first matching line in a list of lines. See match()""" for line in lines: matching=match(line,keyword) if matching!=None: return matching return None
[ "def", "matching_line", "(", "lines", ",", "keyword", ")", ":", "for", "line", "in", "lines", ":", "matching", "=", "match", "(", "line", ",", "keyword", ")", "if", "matching", "!=", "None", ":", "return", "matching", "return", "None" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/rickmote.py#L68-L74
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
rickmote.py
python
match
(line,keyword)
If the first part of line (modulo blanks) matches keyword, returns the end of that line. Otherwise returns None
If the first part of line (modulo blanks) matches keyword, returns the end of that line. Otherwise returns None
[ "If", "the", "first", "part", "of", "line", "(", "modulo", "blanks", ")", "matches", "keyword", "returns", "the", "end", "of", "that", "line", ".", "Otherwise", "returns", "None" ]
def match(line,keyword): """If the first part of line (modulo blanks) matches keyword, returns the end of that line. Otherwise returns None""" line=line.lstrip() length=len(keyword) if line[:length] == keyword: return line[length:] else: return None
[ "def", "match", "(", "line", ",", "keyword", ")", ":", "line", "=", "line", ".", "lstrip", "(", ")", "length", "=", "len", "(", "keyword", ")", "if", "line", "[", ":", "length", "]", "==", "keyword", ":", "return", "line", "[", "length", ":", "]", "else", ":", "return", "None" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/rickmote.py#L76-L84
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
rickmote.py
python
parse_cell
(cell)
return parsed_cell
Applies the rules to the bunch of text describing a cell and returns the corresponding dictionary
Applies the rules to the bunch of text describing a cell and returns the corresponding dictionary
[ "Applies", "the", "rules", "to", "the", "bunch", "of", "text", "describing", "a", "cell", "and", "returns", "the", "corresponding", "dictionary" ]
def parse_cell(cell): """Applies the rules to the bunch of text describing a cell and returns the corresponding dictionary""" parsed_cell={} for key in rules: rule=rules[key] parsed_cell.update({key:rule(cell)}) return parsed_cell
[ "def", "parse_cell", "(", "cell", ")", ":", "parsed_cell", "=", "{", "}", "for", "key", "in", "rules", ":", "rule", "=", "rules", "[", "key", "]", "parsed_cell", ".", "update", "(", "{", "key", ":", "rule", "(", "cell", ")", "}", ")", "return", "parsed_cell" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/rickmote.py#L86-L93
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/dial.py
python
start_app
(host, app_id, data=None)
Starts an application. If your TV is not on will turn it on unless app_id == APP_ID_HOME.
Starts an application.
[ "Starts", "an", "application", "." ]
def start_app(host, app_id, data=None): """ Starts an application. If your TV is not on will turn it on unless app_id == APP_ID_HOME. """ if data is None: data = {"": ""} CC_SESSION.post(_craft_app_url(host, app_id), data=data)
[ "def", "start_app", "(", "host", ",", "app_id", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "data", "=", "{", "\"\"", ":", "\"\"", "}", "CC_SESSION", ".", "post", "(", "_craft_app_url", "(", "host", ",", "app_id", ")", ",", "data", "=", "data", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/dial.py#L21-L29
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/dial.py
python
quit_app
(host, app_id=None)
Quits specified application if it is running. If no app_id specified will quit current running app.
Quits specified application if it is running. If no app_id specified will quit current running app.
[ "Quits", "specified", "application", "if", "it", "is", "running", ".", "If", "no", "app_id", "specified", "will", "quit", "current", "running", "app", "." ]
def quit_app(host, app_id=None): """ Quits specified application if it is running. If no app_id specified will quit current running app. """ if not app_id: status = get_app_status(host) if status: app_id = status.app_id if app_id: CC_SESSION.delete(_craft_app_url(host, app_id))
[ "def", "quit_app", "(", "host", ",", "app_id", "=", "None", ")", ":", "if", "not", "app_id", ":", "status", "=", "get_app_status", "(", "host", ")", "if", "status", ":", "app_id", "=", "status", ".", "app_id", "if", "app_id", ":", "CC_SESSION", ".", "delete", "(", "_craft_app_url", "(", "host", ",", "app_id", ")", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/dial.py#L32-L43
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/dial.py
python
reboot
(host)
Reboots the chromecast.
Reboots the chromecast.
[ "Reboots", "the", "chromecast", "." ]
def reboot(host): """ Reboots the chromecast. """ CC_SESSION.post(FORMAT_BASE_URL.format(host) + "/setup/reboot", data='{"params":"now"}')
[ "def", "reboot", "(", "host", ")", ":", "CC_SESSION", ".", "post", "(", "FORMAT_BASE_URL", ".", "format", "(", "host", ")", "+", "\"/setup/reboot\"", ",", "data", "=", "'{\"params\":\"now\"}'", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/dial.py#L46-L49
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/dial.py
python
get_device_status
(host)
Returns the device status as a named tuple.
Returns the device status as a named tuple.
[ "Returns", "the", "device", "status", "as", "a", "named", "tuple", "." ]
def get_device_status(host): """ Returns the device status as a named tuple. """ try: req = CC_SESSION.get( FORMAT_BASE_URL.format(host) + "/ssdp/device-desc.xml") status_el = ET.fromstring(req.text.encode("UTF-8")) device_info_el = status_el.find(XML_NS_UPNP_DEVICE + "device") api_version_el = status_el.find(XML_NS_UPNP_DEVICE + "specVersion") friendly_name = _read_xml_element(device_info_el, XML_NS_UPNP_DEVICE, "friendlyName", "Unknown Chromecast") model_name = _read_xml_element(device_info_el, XML_NS_UPNP_DEVICE, "modelName", "Unknown model name") manufacturer = _read_xml_element(device_info_el, XML_NS_UPNP_DEVICE, "manufacturer", "Unknown manufacturer") api_version = (int(_read_xml_element(api_version_el, XML_NS_UPNP_DEVICE, "major", -1)), int(_read_xml_element(api_version_el, XML_NS_UPNP_DEVICE, "minor", -1))) return DeviceStatus(friendly_name, model_name, manufacturer, api_version) except (requests.exceptions.RequestException, ET.ParseError): return None
[ "def", "get_device_status", "(", "host", ")", ":", "try", ":", "req", "=", "CC_SESSION", ".", "get", "(", "FORMAT_BASE_URL", ".", "format", "(", "host", ")", "+", "\"/ssdp/device-desc.xml\"", ")", "status_el", "=", "ET", ".", "fromstring", "(", "req", ".", "text", ".", "encode", "(", "\"UTF-8\"", ")", ")", "device_info_el", "=", "status_el", ".", "find", "(", "XML_NS_UPNP_DEVICE", "+", "\"device\"", ")", "api_version_el", "=", "status_el", ".", "find", "(", "XML_NS_UPNP_DEVICE", "+", "\"specVersion\"", ")", "friendly_name", "=", "_read_xml_element", "(", "device_info_el", ",", "XML_NS_UPNP_DEVICE", ",", "\"friendlyName\"", ",", "\"Unknown Chromecast\"", ")", "model_name", "=", "_read_xml_element", "(", "device_info_el", ",", "XML_NS_UPNP_DEVICE", ",", "\"modelName\"", ",", "\"Unknown model name\"", ")", "manufacturer", "=", "_read_xml_element", "(", "device_info_el", ",", "XML_NS_UPNP_DEVICE", ",", "\"manufacturer\"", ",", "\"Unknown manufacturer\"", ")", "api_version", "=", "(", "int", "(", "_read_xml_element", "(", "api_version_el", ",", "XML_NS_UPNP_DEVICE", ",", "\"major\"", ",", "-", "1", ")", ")", ",", "int", "(", "_read_xml_element", "(", "api_version_el", ",", "XML_NS_UPNP_DEVICE", ",", "\"minor\"", ",", "-", "1", ")", ")", ")", "return", "DeviceStatus", "(", "friendly_name", ",", "model_name", ",", "manufacturer", ",", "api_version", ")", "except", "(", "requests", ".", "exceptions", ".", "RequestException", ",", "ET", ".", "ParseError", ")", ":", "return", "None" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/dial.py#L52-L81
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/dial.py
python
get_app_status
(host, app_id=None)
Returns the status of the specified app or else the current running app.
Returns the status of the specified app or else the current running app.
[ "Returns", "the", "status", "of", "the", "specified", "app", "or", "else", "the", "current", "running", "app", "." ]
def get_app_status(host, app_id=None): """ Returns the status of the specified app or else the current running app. """ # /apps/ will redirect to the active app url = (FORMAT_APP_PATH.format(host, app_id) if app_id else FORMAT_BASE_URL.format(host) + "/apps/") try: req = CC_SESSION.get(url) if req.status_code == 204: return None status_el = ET.fromstring(req.text.encode("UTF-8")) options = status_el.find(XML_NS_DIAL + "options").attrib app_id = _read_xml_element(status_el, XML_NS_DIAL, "name", "Unknown application") state = _read_xml_element(status_el, XML_NS_DIAL, "state", "unknown") service_el = status_el.find(XML_NS_CAST + "servicedata") if service_el is not None: service_url = _read_xml_element(service_el, XML_NS_CAST, "connectionSvcURL", None) protocols_el = service_el.find(XML_NS_CAST + "protocols") if protocols_el is not None: protocols = [el.text for el in protocols_el] else: protocols = [] else: service_url = None protocols = [] activity_el = status_el.find(XML_NS_CAST + "activity-status") if activity_el is not None: description = _read_xml_element(activity_el, XML_NS_CAST, "description", app_id) else: description = app_id return AppStatus(app_id, description, state, options, service_url, protocols) except (requests.exceptions.RequestException, ET.ParseError): return None
[ "def", "get_app_status", "(", "host", ",", "app_id", "=", "None", ")", ":", "# /apps/ will redirect to the active app", "url", "=", "(", "FORMAT_APP_PATH", ".", "format", "(", "host", ",", "app_id", ")", "if", "app_id", "else", "FORMAT_BASE_URL", ".", "format", "(", "host", ")", "+", "\"/apps/\"", ")", "try", ":", "req", "=", "CC_SESSION", ".", "get", "(", "url", ")", "if", "req", ".", "status_code", "==", "204", ":", "return", "None", "status_el", "=", "ET", ".", "fromstring", "(", "req", ".", "text", ".", "encode", "(", "\"UTF-8\"", ")", ")", "options", "=", "status_el", ".", "find", "(", "XML_NS_DIAL", "+", "\"options\"", ")", ".", "attrib", "app_id", "=", "_read_xml_element", "(", "status_el", ",", "XML_NS_DIAL", ",", "\"name\"", ",", "\"Unknown application\"", ")", "state", "=", "_read_xml_element", "(", "status_el", ",", "XML_NS_DIAL", ",", "\"state\"", ",", "\"unknown\"", ")", "service_el", "=", "status_el", ".", "find", "(", "XML_NS_CAST", "+", "\"servicedata\"", ")", "if", "service_el", "is", "not", "None", ":", "service_url", "=", "_read_xml_element", "(", "service_el", ",", "XML_NS_CAST", ",", "\"connectionSvcURL\"", ",", "None", ")", "protocols_el", "=", "service_el", ".", "find", "(", "XML_NS_CAST", "+", "\"protocols\"", ")", "if", "protocols_el", "is", "not", "None", ":", "protocols", "=", "[", "el", ".", "text", "for", "el", "in", "protocols_el", "]", "else", ":", "protocols", "=", "[", "]", "else", ":", "service_url", "=", "None", "protocols", "=", "[", "]", "activity_el", "=", "status_el", ".", "find", "(", "XML_NS_CAST", "+", "\"activity-status\"", ")", "if", "activity_el", "is", "not", "None", ":", "description", "=", "_read_xml_element", "(", "activity_el", ",", "XML_NS_CAST", ",", "\"description\"", ",", "app_id", ")", "else", ":", "description", "=", "app_id", "return", "AppStatus", "(", "app_id", ",", "description", ",", "state", ",", "options", ",", "service_url", ",", "protocols", ")", "except", "(", "requests", ".", "exceptions", ".", "RequestException", ",", "ET", ".", "ParseError", ")", ":", "return", "None" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/dial.py#L84-L135
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/dial.py
python
_craft_app_url
(host, app_id=None)
return (FORMAT_APP_PATH.format(host, app_id) if app_id else FORMAT_BASE_URL.format(host))
Helper method to create a ChromeCast url given a host and an optional app_id.
Helper method to create a ChromeCast url given a host and an optional app_id.
[ "Helper", "method", "to", "create", "a", "ChromeCast", "url", "given", "a", "host", "and", "an", "optional", "app_id", "." ]
def _craft_app_url(host, app_id=None): """ Helper method to create a ChromeCast url given a host and an optional app_id. """ return (FORMAT_APP_PATH.format(host, app_id) if app_id else FORMAT_BASE_URL.format(host))
[ "def", "_craft_app_url", "(", "host", ",", "app_id", "=", "None", ")", ":", "return", "(", "FORMAT_APP_PATH", ".", "format", "(", "host", ",", "app_id", ")", "if", "app_id", "else", "FORMAT_BASE_URL", ".", "format", "(", "host", ")", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/dial.py#L138-L142
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/dial.py
python
_read_xml_element
(element, xml_ns, tag_name, default="")
Helper method to read text from an element.
Helper method to read text from an element.
[ "Helper", "method", "to", "read", "text", "from", "an", "element", "." ]
def _read_xml_element(element, xml_ns, tag_name, default=""): """ Helper method to read text from an element. """ try: return element.find(xml_ns + tag_name).text except AttributeError: return default
[ "def", "_read_xml_element", "(", "element", ",", "xml_ns", ",", "tag_name", ",", "default", "=", "\"\"", ")", ":", "try", ":", "return", "element", ".", "find", "(", "xml_ns", "+", "tag_name", ")", ".", "text", "except", "AttributeError", ":", "return", "default" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/dial.py#L145-L151
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/upnp.py
python
discover_chromecasts
(max_devices=None, timeout=DISCOVER_TIMEOUT)
return ips
Sends a message over the network to discover Chromecasts and returns a list of found IP addresses. Inspired by Crimsdings https://github.com/crimsdings/ChromeCast/blob/master/cc_discovery.py
Sends a message over the network to discover Chromecasts and returns a list of found IP addresses.
[ "Sends", "a", "message", "over", "the", "network", "to", "discover", "Chromecasts", "and", "returns", "a", "list", "of", "found", "IP", "addresses", "." ]
def discover_chromecasts(max_devices=None, timeout=DISCOVER_TIMEOUT): """ Sends a message over the network to discover Chromecasts and returns a list of found IP addresses. Inspired by Crimsdings https://github.com/crimsdings/ChromeCast/blob/master/cc_discovery.py """ ips = [] calc_now = dt.datetime.now start = calc_now() try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(SSDP_REQUEST.encode("ascii"), (SSDP_ADDR, SSDP_PORT)) sock.setblocking(0) while True: time_diff = calc_now() - start seconds_left = timeout - time_diff.seconds if seconds_left <= 0: return ips ready = select.select([sock], [], [], seconds_left)[0] if ready: response = sock.recv(1024).decode("ascii") found_ip = found_st = None headers = response.split("\r\n\r\n", 1)[0] for header in headers.split("\r\n"): parts = header.split(": ", 1) # Headers start with something like 'HTTP/1.1 200 OK' # We cannot split that up in key-value pair, so skip if len(parts) != 2: continue key, value = parts if key == "LOCATION": url = urlparse.urlparse(value) found_ip = url.hostname elif key == "ST": found_st = value if found_st == SSDP_ST and found_ip: ips.append(found_ip) if max_devices and len(ips) == max_devices: return ips except socket.error: logging.getLogger(__name__).exception( "Socket error while discovering Chromecasts") finally: sock.close() return ips
[ "def", "discover_chromecasts", "(", "max_devices", "=", "None", ",", "timeout", "=", "DISCOVER_TIMEOUT", ")", ":", "ips", "=", "[", "]", "calc_now", "=", "dt", ".", "datetime", ".", "now", "start", "=", "calc_now", "(", ")", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "sock", ".", "sendto", "(", "SSDP_REQUEST", ".", "encode", "(", "\"ascii\"", ")", ",", "(", "SSDP_ADDR", ",", "SSDP_PORT", ")", ")", "sock", ".", "setblocking", "(", "0", ")", "while", "True", ":", "time_diff", "=", "calc_now", "(", ")", "-", "start", "seconds_left", "=", "timeout", "-", "time_diff", ".", "seconds", "if", "seconds_left", "<=", "0", ":", "return", "ips", "ready", "=", "select", ".", "select", "(", "[", "sock", "]", ",", "[", "]", ",", "[", "]", ",", "seconds_left", ")", "[", "0", "]", "if", "ready", ":", "response", "=", "sock", ".", "recv", "(", "1024", ")", ".", "decode", "(", "\"ascii\"", ")", "found_ip", "=", "found_st", "=", "None", "headers", "=", "response", ".", "split", "(", "\"\\r\\n\\r\\n\"", ",", "1", ")", "[", "0", "]", "for", "header", "in", "headers", ".", "split", "(", "\"\\r\\n\"", ")", ":", "parts", "=", "header", ".", "split", "(", "\": \"", ",", "1", ")", "# Headers start with something like 'HTTP/1.1 200 OK'", "# We cannot split that up in key-value pair, so skip", "if", "len", "(", "parts", ")", "!=", "2", ":", "continue", "key", ",", "value", "=", "parts", "if", "key", "==", "\"LOCATION\"", ":", "url", "=", "urlparse", ".", "urlparse", "(", "value", ")", "found_ip", "=", "url", ".", "hostname", "elif", "key", "==", "\"ST\"", ":", "found_st", "=", "value", "if", "found_st", "==", "SSDP_ST", "and", "found_ip", ":", "ips", ".", "append", "(", "found_ip", ")", "if", "max_devices", "and", "len", "(", "ips", ")", "==", "max_devices", ":", "return", "ips", "except", "socket", ".", "error", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "exception", "(", "\"Socket error while discovering Chromecasts\"", ")", "finally", ":", "sock", ".", "close", "(", ")", "return", "ips" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/upnp.py#L30-L98
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/config.py
python
get_possible_app_ids
()
Returns all possible app ids.
Returns all possible app ids.
[ "Returns", "all", "possible", "app", "ids", "." ]
def get_possible_app_ids(): """ Returns all possible app ids. """ try: req = requests.get( "https://clients3.google.com/cast/chromecast/device/baseconfig") data = json.loads(req.text[4:]) return [app['app_id'] for app in data['applications']] + \ data["enabled_app_ids"] except ValueError: # If json fails to parse return []
[ "def", "get_possible_app_ids", "(", ")", ":", "try", ":", "req", "=", "requests", ".", "get", "(", "\"https://clients3.google.com/cast/chromecast/device/baseconfig\"", ")", "data", "=", "json", ".", "loads", "(", "req", ".", "text", "[", "4", ":", "]", ")", "return", "[", "app", "[", "'app_id'", "]", "for", "app", "in", "data", "[", "'applications'", "]", "]", "+", "data", "[", "\"enabled_app_ids\"", "]", "except", "ValueError", ":", "# If json fails to parse", "return", "[", "]" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/config.py#L34-L47
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/config.py
python
get_app_config
(app_id)
Get specific configuration for 'app_id'.
Get specific configuration for 'app_id'.
[ "Get", "specific", "configuration", "for", "app_id", "." ]
def get_app_config(app_id): """ Get specific configuration for 'app_id'. """ try: req = requests.get( ("https://clients3.google.com/" "cast/chromecast/device/app?a={}").format(app_id)) return json.loads(req.text[4:]) if req.status_code == 200 else {} except ValueError: # If json fails to parse return {}
[ "def", "get_app_config", "(", "app_id", ")", ":", "try", ":", "req", "=", "requests", ".", "get", "(", "(", "\"https://clients3.google.com/\"", "\"cast/chromecast/device/app?a={}\"", ")", ".", "format", "(", "app_id", ")", ")", "return", "json", ".", "loads", "(", "req", ".", "text", "[", "4", ":", "]", ")", "if", "req", ".", "status_code", "==", "200", "else", "{", "}", "except", "ValueError", ":", "# If json fails to parse", "return", "{", "}" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/config.py#L50-L61
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
create_websocket_client
(app_status)
return client
Creates and returns a RAMP client based on the supplied app status. Will return None if RAMP client is not supported. Will raise ValueError if unable to retrieve the websocket url.
Creates and returns a RAMP client based on the supplied app status. Will return None if RAMP client is not supported. Will raise ValueError if unable to retrieve the websocket url.
[ "Creates", "and", "returns", "a", "RAMP", "client", "based", "on", "the", "supplied", "app", "status", ".", "Will", "return", "None", "if", "RAMP", "client", "is", "not", "supported", ".", "Will", "raise", "ValueError", "if", "unable", "to", "retrieve", "the", "websocket", "url", "." ]
def create_websocket_client(app_status): """ Creates and returns a RAMP client based on the supplied app status. Will return None if RAMP client is not supported. Will raise ValueError if unable to retrieve the websocket url. """ # Check if current app has no service url or no protocols. if not app_status.service_url or not app_status.service_protocols: return None req = requests.post(app_status.service_url, data="{}".encode("ascii"), headers={"Content-Type": "application/json"}) if req.status_code != 200: raise error.ConnectionError( "Could not retrieve websocket url ({}).".format(req.status_code)) conn_data = json.loads(req.text) client = ChromecastWebSocketClient(conn_data['URL'], app_status.service_protocols) client.connect() atexit.register(_clean_open_clients) return client
[ "def", "create_websocket_client", "(", "app_status", ")", ":", "# Check if current app has no service url or no protocols.", "if", "not", "app_status", ".", "service_url", "or", "not", "app_status", ".", "service_protocols", ":", "return", "None", "req", "=", "requests", ".", "post", "(", "app_status", ".", "service_url", ",", "data", "=", "\"{}\"", ".", "encode", "(", "\"ascii\"", ")", ",", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", "}", ")", "if", "req", ".", "status_code", "!=", "200", ":", "raise", "error", ".", "ConnectionError", "(", "\"Could not retrieve websocket url ({}).\"", ".", "format", "(", "req", ".", "status_code", ")", ")", "conn_data", "=", "json", ".", "loads", "(", "req", ".", "text", ")", "client", "=", "ChromecastWebSocketClient", "(", "conn_data", "[", "'URL'", "]", ",", "app_status", ".", "service_protocols", ")", "client", ".", "connect", "(", ")", "atexit", ".", "register", "(", "_clean_open_clients", ")", "return", "client" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L87-L115
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
_clean_open_clients
()
Called on exit of Python to close open clients.
Called on exit of Python to close open clients.
[ "Called", "on", "exit", "of", "Python", "to", "close", "open", "clients", "." ]
def _clean_open_clients(): """ Called on exit of Python to close open clients. """ for client_weakref in list(_OPEN_CLIENTS): client = client_weakref() if client and not client.terminated: client.close_connection()
[ "def", "_clean_open_clients", "(", ")", ":", "for", "client_weakref", "in", "list", "(", "_OPEN_CLIENTS", ")", ":", "client", "=", "client_weakref", "(", ")", "if", "client", "and", "not", "client", ".", "terminated", ":", "client", ".", "close_connection", "(", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L118-L124
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
ChromecastWebSocketClient.opened
(self)
When connection is opened initiate the protocol handlers.
When connection is opened initiate the protocol handlers.
[ "When", "connection", "is", "opened", "initiate", "the", "protocol", "handlers", "." ]
def opened(self): """ When connection is opened initiate the protocol handlers. """ _OPEN_CLIENTS.append(self._weakref) self.handlers[PROTOCOL_COMMAND] = CommandSubprotocol(self) _known_prot = KNOWN_PROTOCOLS # Instantiate supported subprotocols. for protocol in self.supported_protocols: handler = _known_prot.get(protocol) if handler: self.handlers[protocol] = handler(self) else: self.logger.warning( "Unsupported protocol: {}".format(protocol))
[ "def", "opened", "(", "self", ")", ":", "_OPEN_CLIENTS", ".", "append", "(", "self", ".", "_weakref", ")", "self", ".", "handlers", "[", "PROTOCOL_COMMAND", "]", "=", "CommandSubprotocol", "(", "self", ")", "_known_prot", "=", "KNOWN_PROTOCOLS", "# Instantiate supported subprotocols.", "for", "protocol", "in", "self", ".", "supported_protocols", ":", "handler", "=", "_known_prot", ".", "get", "(", "protocol", ")", "if", "handler", ":", "self", ".", "handlers", "[", "protocol", "]", "=", "handler", "(", "self", ")", "else", ":", "self", ".", "logger", ".", "warning", "(", "\"Unsupported protocol: {}\"", ".", "format", "(", "protocol", ")", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L139-L155
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
ChromecastWebSocketClient.closed
(self, code, reason=None)
Clear protocol handlers when connection is lost.
Clear protocol handlers when connection is lost.
[ "Clear", "protocol", "handlers", "when", "connection", "is", "lost", "." ]
def closed(self, code, reason=None): """ Clear protocol handlers when connection is lost. """ # Clear reference to client _OPEN_CLIENTS.remove(self._weakref) for handler in self.handlers.values(): handler.client = None self.handlers.clear()
[ "def", "closed", "(", "self", ",", "code", ",", "reason", "=", "None", ")", ":", "# Clear reference to client", "_OPEN_CLIENTS", ".", "remove", "(", "self", ".", "_weakref", ")", "for", "handler", "in", "self", ".", "handlers", ".", "values", "(", ")", ":", "handler", ".", "client", "=", "None", "self", ".", "handlers", ".", "clear", "(", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L157-L165
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
ChromecastWebSocketClient.received_message
(self, message)
When a new message is received.
When a new message is received.
[ "When", "a", "new", "message", "is", "received", "." ]
def received_message(self, message): """ When a new message is received. """ # We do not support binary message if message.is_binary: return False try: protocol, data = json.loads(message.data.decode('utf8')) except ValueError: # If error while parsing JSON # if unpack error: more then 2 items in the list logging.getLogger(__name__).exception( "Error parsing incoming message: {}".format( message.data.decode("utf8"))) return if _DEBUG: logging.getLogger(__name__).info("Receiving {}".format(data)) handler = self.handlers.get(protocol) if handler: handler._receive_protocol(data) # pylint: disable=protected-access else: logging.getLogger(__name__).warning( "Unknown protocol received: {}, {}".format(protocol, data))
[ "def", "received_message", "(", "self", ",", "message", ")", ":", "# We do not support binary message", "if", "message", ".", "is_binary", ":", "return", "False", "try", ":", "protocol", ",", "data", "=", "json", ".", "loads", "(", "message", ".", "data", ".", "decode", "(", "'utf8'", ")", ")", "except", "ValueError", ":", "# If error while parsing JSON", "# if unpack error: more then 2 items in the list", "logging", ".", "getLogger", "(", "__name__", ")", ".", "exception", "(", "\"Error parsing incoming message: {}\"", ".", "format", "(", "message", ".", "data", ".", "decode", "(", "\"utf8\"", ")", ")", ")", "return", "if", "_DEBUG", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "info", "(", "\"Receiving {}\"", ".", "format", "(", "data", ")", ")", "handler", "=", "self", ".", "handlers", ".", "get", "(", "protocol", ")", "if", "handler", ":", "handler", ".", "_receive_protocol", "(", "data", ")", "# pylint: disable=protected-access", "else", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "warning", "(", "\"Unknown protocol received: {}, {}\"", ".", "format", "(", "protocol", ",", "data", ")", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L167-L194
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
BaseSubprotocol._send_protocol
(self, data)
Default handler for sending messages as subprotocol.
Default handler for sending messages as subprotocol.
[ "Default", "handler", "for", "sending", "messages", "as", "subprotocol", "." ]
def _send_protocol(self, data): """ Default handler for sending messages as subprotocol. """ if _DEBUG: self.logger.info("Sending {}".format(data)) if not self.client: raise error.ConnectionError("Not connected to Chromecast") try: self.client.send(json.dumps([self.protocol, data]).encode("utf8")) except socket.error: # if an error occured sending data over the socket raise error.ConnectionError("Error communicating with Chromecast")
[ "def", "_send_protocol", "(", "self", ",", "data", ")", ":", "if", "_DEBUG", ":", "self", ".", "logger", ".", "info", "(", "\"Sending {}\"", ".", "format", "(", "data", ")", ")", "if", "not", "self", ".", "client", ":", "raise", "error", ".", "ConnectionError", "(", "\"Not connected to Chromecast\"", ")", "try", ":", "self", ".", "client", ".", "send", "(", "json", ".", "dumps", "(", "[", "self", ".", "protocol", ",", "data", "]", ")", ".", "encode", "(", "\"utf8\"", ")", ")", "except", "socket", ".", "error", ":", "# if an error occured sending data over the socket", "raise", "error", ".", "ConnectionError", "(", "\"Error communicating with Chromecast\"", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L206-L219
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
BaseSubprotocol._receive_protocol
(self, data)
Default handler for receiving messages as subprotocol.
Default handler for receiving messages as subprotocol.
[ "Default", "handler", "for", "receiving", "messages", "as", "subprotocol", "." ]
def _receive_protocol(self, data): """ Default handler for receiving messages as subprotocol. """ self.logger.warning( "Unhandled {} message: {}".format(self.protocol, data))
[ "def", "_receive_protocol", "(", "self", ",", "data", ")", ":", "self", ".", "logger", ".", "warning", "(", "\"Unhandled {} message: {}\"", ".", "format", "(", "self", ".", "protocol", ",", "data", ")", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L221-L224
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
BaseSubprotocol.is_active
(self)
return not self.client.terminated
Returns if this subprotocol is active.
Returns if this subprotocol is active.
[ "Returns", "if", "this", "subprotocol", "is", "active", "." ]
def is_active(self): """ Returns if this subprotocol is active. """ return not self.client.terminated
[ "def", "is_active", "(", "self", ")", ":", "return", "not", "self", ".", "client", ".", "terminated" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L227-L229
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
CommandSubprotocol._receive_protocol
(self, data)
Handles an incoming COMMAND message.
Handles an incoming COMMAND message.
[ "Handles", "an", "incoming", "COMMAND", "message", "." ]
def _receive_protocol(self, data): """ Handles an incoming COMMAND message. """ if data[COMMAND_ATTR_TYPE] == COMMAND_TYPE_PING: self._send_protocol({COMMAND_ATTR_TYPE: COMMAND_TYPE_PONG}) else: BaseSubprotocol._receive_protocol(self, data)
[ "def", "_receive_protocol", "(", "self", ",", "data", ")", ":", "if", "data", "[", "COMMAND_ATTR_TYPE", "]", "==", "COMMAND_TYPE_PING", ":", "self", ".", "_send_protocol", "(", "{", "COMMAND_ATTR_TYPE", ":", "COMMAND_TYPE_PONG", "}", ")", "else", ":", "BaseSubprotocol", ".", "_receive_protocol", "(", "self", ",", "data", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L238-L244
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol._receive_protocol
(self, data)
Handles an incoming Ramp message.
Handles an incoming Ramp message.
[ "Handles", "an", "incoming", "Ramp", "message", "." ]
def _receive_protocol(self, data): """ Handles an incoming Ramp message. """ message_type = data[RAMP_ATTR_TYPE] if message_type == RAMP_TYPE_STATUS: self._update_status(data[RAMP_ATTR_STATUS]) elif message_type == RAMP_TYPE_RESPONSE: # Match it with the command that we send try: cmd_type, cmd_event = \ self.commands.pop(data[RAMP_ATTR_CMD_ID]) except KeyError: # If CMD_ID did not exist or we do not recognize command return # Handle response, currently no response handlers if cmd_type in (RAMP_TYPE_PLAY, RAMP_TYPE_VOLUME, RAMP_TYPE_INFO): self._update_status(data[RAMP_ATTR_STATUS]) else: self.logger.warning( "Unhandled response for command {}: {}".format( cmd_type, data)) # Alert code that is waiting for this command to get response if cmd_event: cmd_event.set() else: BaseSubprotocol._receive_protocol(self, data)
[ "def", "_receive_protocol", "(", "self", ",", "data", ")", ":", "message_type", "=", "data", "[", "RAMP_ATTR_TYPE", "]", "if", "message_type", "==", "RAMP_TYPE_STATUS", ":", "self", ".", "_update_status", "(", "data", "[", "RAMP_ATTR_STATUS", "]", ")", "elif", "message_type", "==", "RAMP_TYPE_RESPONSE", ":", "# Match it with the command that we send", "try", ":", "cmd_type", ",", "cmd_event", "=", "self", ".", "commands", ".", "pop", "(", "data", "[", "RAMP_ATTR_CMD_ID", "]", ")", "except", "KeyError", ":", "# If CMD_ID did not exist or we do not recognize command", "return", "# Handle response, currently no response handlers", "if", "cmd_type", "in", "(", "RAMP_TYPE_PLAY", ",", "RAMP_TYPE_VOLUME", ",", "RAMP_TYPE_INFO", ")", ":", "self", ".", "_update_status", "(", "data", "[", "RAMP_ATTR_STATUS", "]", ")", "else", ":", "self", ".", "logger", ".", "warning", "(", "\"Unhandled response for command {}: {}\"", ".", "format", "(", "cmd_type", ",", "data", ")", ")", "# Alert code that is waiting for this command to get response", "if", "cmd_event", ":", "cmd_event", ".", "set", "(", ")", "else", ":", "BaseSubprotocol", ".", "_receive_protocol", "(", "self", ",", "data", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L259-L292
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol._send_ramp
(self, data, blocking=False)
Sends a RAMP message. Set blocking=True to wait till the Chromecast sends a response to the command.
Sends a RAMP message. Set blocking=True to wait till the Chromecast sends a response to the command.
[ "Sends", "a", "RAMP", "message", ".", "Set", "blocking", "=", "True", "to", "wait", "till", "the", "Chromecast", "sends", "a", "response", "to", "the", "command", "." ]
def _send_ramp(self, data, blocking=False): """ Sends a RAMP message. Set blocking=True to wait till the Chromecast sends a response to the command. """ data[RAMP_ATTR_CMD_ID] = self.command_id event = threading.Event() if blocking else None # Save type to match later with response self.commands[self.command_id] = (data[RAMP_ATTR_TYPE], event) self._send_protocol(data) self.command_id += 1 if blocking: event.wait()
[ "def", "_send_ramp", "(", "self", ",", "data", ",", "blocking", "=", "False", ")", ":", "data", "[", "RAMP_ATTR_CMD_ID", "]", "=", "self", ".", "command_id", "event", "=", "threading", ".", "Event", "(", ")", "if", "blocking", "else", "None", "# Save type to match later with response", "self", ".", "commands", "[", "self", ".", "command_id", "]", "=", "(", "data", "[", "RAMP_ATTR_TYPE", "]", ",", "event", ")", "self", ".", "_send_protocol", "(", "data", ")", "self", ".", "command_id", "+=", "1", "if", "blocking", ":", "event", ".", "wait", "(", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L295-L313
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.is_playing
(self)
return self.is_active and self.state == RAMP_STATE_PLAYING
Property that represents if content is being played.
Property that represents if content is being played.
[ "Property", "that", "represents", "if", "content", "is", "being", "played", "." ]
def is_playing(self): """ Property that represents if content is being played. """ return self.is_active and self.state == RAMP_STATE_PLAYING
[ "def", "is_playing", "(", "self", ")", ":", "return", "self", ".", "is_active", "and", "self", ".", "state", "==", "RAMP_STATE_PLAYING" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L316-L318
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.play
(self)
Send the PLAY-command to the RAMP-target.
Send the PLAY-command to the RAMP-target.
[ "Send", "the", "PLAY", "-", "command", "to", "the", "RAMP", "-", "target", "." ]
def play(self): """ Send the PLAY-command to the RAMP-target. """ self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_PLAY})
[ "def", "play", "(", "self", ")", ":", "self", ".", "_send_ramp", "(", "{", "RAMP_ATTR_TYPE", ":", "RAMP_TYPE_PLAY", "}", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L320-L322
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.pause
(self)
Send the PAUSE-command to the RAMP-target.
Send the PAUSE-command to the RAMP-target.
[ "Send", "the", "PAUSE", "-", "command", "to", "the", "RAMP", "-", "target", "." ]
def pause(self): """ Send the PAUSE-command to the RAMP-target. """ # The STOP command actually pauses the media self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_STOP})
[ "def", "pause", "(", "self", ")", ":", "# The STOP command actually pauses the media", "self", ".", "_send_ramp", "(", "{", "RAMP_ATTR_TYPE", ":", "RAMP_TYPE_STOP", "}", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L324-L327
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.playpause
(self)
Plays if paused, pauses if playing.
Plays if paused, pauses if playing.
[ "Plays", "if", "paused", "pauses", "if", "playing", "." ]
def playpause(self): """ Plays if paused, pauses if playing. """ if self.state == RAMP_STATE_PLAYING: self.pause() else: self.play()
[ "def", "playpause", "(", "self", ")", ":", "if", "self", ".", "state", "==", "RAMP_STATE_PLAYING", ":", "self", ".", "pause", "(", ")", "else", ":", "self", ".", "play", "(", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L329-L334
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.seek
(self, seconds)
Seek within the content played at RAMP-target.
Seek within the content played at RAMP-target.
[ "Seek", "within", "the", "content", "played", "at", "RAMP", "-", "target", "." ]
def seek(self, seconds): """ Seek within the content played at RAMP-target. """ self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_PLAY, RAMP_ATTR_POSITION: seconds})
[ "def", "seek", "(", "self", ",", "seconds", ")", ":", "self", ".", "_send_ramp", "(", "{", "RAMP_ATTR_TYPE", ":", "RAMP_TYPE_PLAY", ",", "RAMP_ATTR_POSITION", ":", "seconds", "}", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L336-L339
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.rewind
(self)
Rewinds current media item.
Rewinds current media item.
[ "Rewinds", "current", "media", "item", "." ]
def rewind(self): """ Rewinds current media item. """ self.seek(0)
[ "def", "rewind", "(", "self", ")", ":", "self", ".", "seek", "(", "0", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L341-L343
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.next
(self)
Skip to the next content at the RAMP-target.
Skip to the next content at the RAMP-target.
[ "Skip", "to", "the", "next", "content", "at", "the", "RAMP", "-", "target", "." ]
def next(self): """ Skip to the next content at the RAMP-target. """ if self.duration != 0: self.seek(self.duration-.1)
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "duration", "!=", "0", ":", "self", ".", "seek", "(", "self", ".", "duration", "-", ".1", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L345-L348
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.set_volume
(self, volume)
Set volume at the RAMP-target.
Set volume at the RAMP-target.
[ "Set", "volume", "at", "the", "RAMP", "-", "target", "." ]
def set_volume(self, volume): """ Set volume at the RAMP-target. """ # volume is double between 0 and 1 self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_VOLUME, RAMP_ATTR_VOLUME: volume})
[ "def", "set_volume", "(", "self", ",", "volume", ")", ":", "# volume is double between 0 and 1", "self", ".", "_send_ramp", "(", "{", "RAMP_ATTR_TYPE", ":", "RAMP_TYPE_VOLUME", ",", "RAMP_ATTR_VOLUME", ":", "volume", "}", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L350-L354
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.volume_up
(self)
Increases volume.
Increases volume.
[ "Increases", "volume", "." ]
def volume_up(self): """ Increases volume. """ if self.volume < 1: self.set_volume(min(self.volume+.1, 1))
[ "def", "volume_up", "(", "self", ")", ":", "if", "self", ".", "volume", "<", "1", ":", "self", ".", "set_volume", "(", "min", "(", "self", ".", "volume", "+", ".1", ",", "1", ")", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L356-L359
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.volume_down
(self)
Decreases volume.
Decreases volume.
[ "Decreases", "volume", "." ]
def volume_down(self): """ Decreases volume. """ if self.volume > 0: self.set_volume(max(self.volume-.1, 0))
[ "def", "volume_down", "(", "self", ")", ":", "if", "self", ".", "volume", ">", "0", ":", "self", ".", "set_volume", "(", "max", "(", "self", ".", "volume", "-", ".1", ",", "0", ")", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L361-L364
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.refresh
(self)
Refresh data at the RAMP-target.
Refresh data at the RAMP-target.
[ "Refresh", "data", "at", "the", "RAMP", "-", "target", "." ]
def refresh(self): """ Refresh data at the RAMP-target. """ self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_INFO})
[ "def", "refresh", "(", "self", ")", ":", "self", ".", "_send_ramp", "(", "{", "RAMP_ATTR_TYPE", ":", "RAMP_TYPE_INFO", "}", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L366-L368
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol._update_status
(self, status)
Updates the RAMP status.
Updates the RAMP status.
[ "Updates", "the", "RAMP", "status", "." ]
def _update_status(self, status): """ Updates the RAMP status. """ con_inf = status.get(RAMP_ATTR_CONTENT_INFO, {}) self.state = status.get(RAMP_STATUS_ATTR_STATE, 0) self.volume = status.get(RAMP_STATUS_ATTR_VOLUME, 1) self.muted = status.get(RAMP_STATUS_ATTR_MUTED, False) self.content_id = status.get(RAMP_STATUS_ATTR_CONTENT_ID) self.title = status.get(RAMP_STATUS_ATTR_TITLE) self.artist = con_inf.get(RAMP_STATUS_CONTENT_INFO_ATTR_ARTIST) self.album = con_inf.get(RAMP_STATUS_CONTENT_INFO_ATTR_ALBUM_TITLE) self._current_time = status.get(RAMP_STATUS_ATTR_CURRENT_TIME, 0) self.duration = status.get(RAMP_STATUS_ATTR_DURATION, 0) self.image_url = status.get(RAMP_STATUS_ATTR_IMAGE_URL) self.time_progress = status.get(RAMP_ATTR_TIME_PROGRESS, False) self.last_updated = dt.datetime.now()
[ "def", "_update_status", "(", "self", ",", "status", ")", ":", "con_inf", "=", "status", ".", "get", "(", "RAMP_ATTR_CONTENT_INFO", ",", "{", "}", ")", "self", ".", "state", "=", "status", ".", "get", "(", "RAMP_STATUS_ATTR_STATE", ",", "0", ")", "self", ".", "volume", "=", "status", ".", "get", "(", "RAMP_STATUS_ATTR_VOLUME", ",", "1", ")", "self", ".", "muted", "=", "status", ".", "get", "(", "RAMP_STATUS_ATTR_MUTED", ",", "False", ")", "self", ".", "content_id", "=", "status", ".", "get", "(", "RAMP_STATUS_ATTR_CONTENT_ID", ")", "self", ".", "title", "=", "status", ".", "get", "(", "RAMP_STATUS_ATTR_TITLE", ")", "self", ".", "artist", "=", "con_inf", ".", "get", "(", "RAMP_STATUS_CONTENT_INFO_ATTR_ARTIST", ")", "self", ".", "album", "=", "con_inf", ".", "get", "(", "RAMP_STATUS_CONTENT_INFO_ATTR_ALBUM_TITLE", ")", "self", ".", "_current_time", "=", "status", ".", "get", "(", "RAMP_STATUS_ATTR_CURRENT_TIME", ",", "0", ")", "self", ".", "duration", "=", "status", ".", "get", "(", "RAMP_STATUS_ATTR_DURATION", ",", "0", ")", "self", ".", "image_url", "=", "status", ".", "get", "(", "RAMP_STATUS_ATTR_IMAGE_URL", ")", "self", ".", "time_progress", "=", "status", ".", "get", "(", "RAMP_ATTR_TIME_PROGRESS", ",", "False", ")", "self", ".", "last_updated", "=", "dt", ".", "datetime", ".", "now", "(", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L370-L386
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/websocket.py
python
RampSubprotocol.current_time
(self)
Returns current time of the content.
Returns current time of the content.
[ "Returns", "current", "time", "of", "the", "content", "." ]
def current_time(self): """ Returns current time of the content. """ # If time is progressing we have to calculate the current time based on # time the status was retrieved and the then current time. if self.time_progress: timediff = dt.datetime.now() - self.last_updated return min(self._current_time + timediff.seconds, self.duration) else: return self._current_time
[ "def", "current_time", "(", "self", ")", ":", "# If time is progressing we have to calculate the current time based on", "# time the status was retrieved and the then current time.", "if", "self", ".", "time_progress", ":", "timediff", "=", "dt", ".", "datetime", ".", "now", "(", ")", "-", "self", ".", "last_updated", "return", "min", "(", "self", ".", "_current_time", "+", "timediff", ".", "seconds", ",", "self", ".", "duration", ")", "else", ":", "return", "self", ".", "_current_time" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/websocket.py#L389-L400
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
play_youtube_video
(video_id, host=None)
Starts the YouTube app if it is not running and plays specified video.
Starts the YouTube app if it is not running and plays specified video.
[ "Starts", "the", "YouTube", "app", "if", "it", "is", "not", "running", "and", "plays", "specified", "video", "." ]
def play_youtube_video(video_id, host=None): """ Starts the YouTube app if it is not running and plays specified video. """ if not host: host = _auto_select_chromecast() start_app(host, APP_ID["YOUTUBE"], {"v": video_id})
[ "def", "play_youtube_video", "(", "video_id", ",", "host", "=", "None", ")", ":", "if", "not", "host", ":", "host", "=", "_auto_select_chromecast", "(", ")", "start_app", "(", "host", ",", "APP_ID", "[", "\"YOUTUBE\"", "]", ",", "{", "\"v\"", ":", "video_id", "}", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L17-L24
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
play_youtube_playlist
(playlist_id, host=None)
Starts the YouTube app if it is not running and plays specified playlist.
Starts the YouTube app if it is not running and plays specified playlist.
[ "Starts", "the", "YouTube", "app", "if", "it", "is", "not", "running", "and", "plays", "specified", "playlist", "." ]
def play_youtube_playlist(playlist_id, host=None): """ Starts the YouTube app if it is not running and plays specified playlist. """ if not host: host = _auto_select_chromecast() start_app(host, APP_ID["YOUTUBE"], {"listType": "playlist", "list": playlist_id})
[ "def", "play_youtube_playlist", "(", "playlist_id", ",", "host", "=", "None", ")", ":", "if", "not", "host", ":", "host", "=", "_auto_select_chromecast", "(", ")", "start_app", "(", "host", ",", "APP_ID", "[", "\"YOUTUBE\"", "]", ",", "{", "\"listType\"", ":", "\"playlist\"", ",", "\"list\"", ":", "playlist_id", "}", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L27-L35
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
_auto_select_chromecast
()
Discovers local Chromecasts and returns first one found. Raises exception if none can be found.
Discovers local Chromecasts and returns first one found. Raises exception if none can be found.
[ "Discovers", "local", "Chromecasts", "and", "returns", "first", "one", "found", ".", "Raises", "exception", "if", "none", "can", "be", "found", "." ]
def _auto_select_chromecast(): """ Discovers local Chromecasts and returns first one found. Raises exception if none can be found. """ ips = discover_chromecasts(1) if ips: return ips[0] else: raise NoChromecastFoundError("Unable to detect Chromecast")
[ "def", "_auto_select_chromecast", "(", ")", ":", "ips", "=", "discover_chromecasts", "(", "1", ")", "if", "ips", ":", "return", "ips", "[", "0", "]", "else", ":", "raise", "NoChromecastFoundError", "(", "\"Unable to detect Chromecast\"", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L38-L48
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
PyChromecast.app_id
(self)
return self.app.app_id if self.app else None
Returns the current app_id.
Returns the current app_id.
[ "Returns", "the", "current", "app_id", "." ]
def app_id(self): """ Returns the current app_id. """ return self.app.app_id if self.app else None
[ "def", "app_id", "(", "self", ")", ":", "return", "self", ".", "app", ".", "app_id", "if", "self", ".", "app", "else", "None" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L73-L75
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
PyChromecast.app_description
(self)
return self.app.description if self.app else None
Returns the name of the current running app.
Returns the name of the current running app.
[ "Returns", "the", "name", "of", "the", "current", "running", "app", "." ]
def app_description(self): """ Returns the name of the current running app. """ return self.app.description if self.app else None
[ "def", "app_description", "(", "self", ")", ":", "return", "self", ".", "app", ".", "description", "if", "self", ".", "app", "else", "None" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L78-L80
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
PyChromecast.get_protocol
(self, protocol)
Returns the current RAMP content info and controls.
Returns the current RAMP content info and controls.
[ "Returns", "the", "current", "RAMP", "content", "info", "and", "controls", "." ]
def get_protocol(self, protocol): """ Returns the current RAMP content info and controls. """ if self.websocket_client: return self.websocket_client.handlers.get(protocol) else: return None
[ "def", "get_protocol", "(", "self", ",", "protocol", ")", ":", "if", "self", ".", "websocket_client", ":", "return", "self", ".", "websocket_client", ".", "handlers", ".", "get", "(", "protocol", ")", "else", ":", "return", "None" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L82-L87
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
PyChromecast.refresh
(self)
Queries the Chromecast for the current status. Starts a websocket client if possible.
Queries the Chromecast for the current status. Starts a websocket client if possible.
[ "Queries", "the", "Chromecast", "for", "the", "current", "status", ".", "Starts", "a", "websocket", "client", "if", "possible", "." ]
def refresh(self): """ Queries the Chromecast for the current status. Starts a websocket client if possible. """ self.logger.info("Refreshing app status") # If we are refreshing but a refresh was planned, cancel that one with self._refresh_lock: if self._refresh_timer: self._refresh_timer.cancel() self._refresh_timer = None cur_app = self.app cur_ws = self.websocket_client self.app = app = get_app_status(self.host) # If no previous app and no new app there is nothing to do if not cur_app and not app: is_diff_app = False else: is_diff_app = (not cur_app and app or cur_app and not app or cur_app.app_id != app.app_id) # Clean up websocket if: # - there is a different app and a connection exists # - if it is the same app but the connection is terminated if cur_ws and (is_diff_app or cur_ws.terminated): if not cur_ws.terminated: cur_ws.close_connection() self.websocket_client = cur_ws = None # Create a new websocket client if there is no connection if not cur_ws and app: try: # If the current app is not capable of a websocket client # This method will return None so nothing is lost self.websocket_client = cur_ws = create_websocket_client(app) except ConnectionError: pass # Ramp service does not always immediately show up in the app # status. If we do not have a websocket client but the app is # known to be RAMP controllable, then plan refresh. if not cur_ws and app.app_id in RAMP_ENABLED: self._delayed_refresh()
[ "def", "refresh", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Refreshing app status\"", ")", "# If we are refreshing but a refresh was planned, cancel that one", "with", "self", ".", "_refresh_lock", ":", "if", "self", ".", "_refresh_timer", ":", "self", ".", "_refresh_timer", ".", "cancel", "(", ")", "self", ".", "_refresh_timer", "=", "None", "cur_app", "=", "self", ".", "app", "cur_ws", "=", "self", ".", "websocket_client", "self", ".", "app", "=", "app", "=", "get_app_status", "(", "self", ".", "host", ")", "# If no previous app and no new app there is nothing to do", "if", "not", "cur_app", "and", "not", "app", ":", "is_diff_app", "=", "False", "else", ":", "is_diff_app", "=", "(", "not", "cur_app", "and", "app", "or", "cur_app", "and", "not", "app", "or", "cur_app", ".", "app_id", "!=", "app", ".", "app_id", ")", "# Clean up websocket if:", "# - there is a different app and a connection exists", "# - if it is the same app but the connection is terminated", "if", "cur_ws", "and", "(", "is_diff_app", "or", "cur_ws", ".", "terminated", ")", ":", "if", "not", "cur_ws", ".", "terminated", ":", "cur_ws", ".", "close_connection", "(", ")", "self", ".", "websocket_client", "=", "cur_ws", "=", "None", "# Create a new websocket client if there is no connection", "if", "not", "cur_ws", "and", "app", ":", "try", ":", "# If the current app is not capable of a websocket client", "# This method will return None so nothing is lost", "self", ".", "websocket_client", "=", "cur_ws", "=", "create_websocket_client", "(", "app", ")", "except", "ConnectionError", ":", "pass", "# Ramp service does not always immediately show up in the app", "# status. If we do not have a websocket client but the app is", "# known to be RAMP controllable, then plan refresh.", "if", "not", "cur_ws", "and", "app", ".", "app_id", "in", "RAMP_ENABLED", ":", "self", ".", "_delayed_refresh", "(", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L89-L139
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
PyChromecast.start_app
(self, app_id, data=None)
Start an app on the Chromecast.
Start an app on the Chromecast.
[ "Start", "an", "app", "on", "the", "Chromecast", "." ]
def start_app(self, app_id, data=None): """ Start an app on the Chromecast. """ self.logger.info("Starting app {}".format(app_id)) # data parameter has to contain atleast 1 key # or else some apps won't show start_app(self.host, app_id, data) self._delayed_refresh()
[ "def", "start_app", "(", "self", ",", "app_id", ",", "data", "=", "None", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Starting app {}\"", ".", "format", "(", "app_id", ")", ")", "# data parameter has to contain atleast 1 key", "# or else some apps won't show", "start_app", "(", "self", ".", "host", ",", "app_id", ",", "data", ")", "self", ".", "_delayed_refresh", "(", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L141-L149
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
PyChromecast.quit_app
(self)
Tells the Chromecast to quit current app_id.
Tells the Chromecast to quit current app_id.
[ "Tells", "the", "Chromecast", "to", "quit", "current", "app_id", "." ]
def quit_app(self): """ Tells the Chromecast to quit current app_id. """ self.logger.info("Quiting current app") quit_app(self.host) self._delayed_refresh()
[ "def", "quit_app", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Quiting current app\"", ")", "quit_app", "(", "self", ".", "host", ")", "self", ".", "_delayed_refresh", "(", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L151-L157
BishopFox/rickmote
2a8469657f9de7d6ee1d4cc65ce83235c1e582d9
pychromecast/__init__.py
python
PyChromecast._delayed_refresh
(self)
Give the ChromeCast time to start the app, then refresh app.
Give the ChromeCast time to start the app, then refresh app.
[ "Give", "the", "ChromeCast", "time", "to", "start", "the", "app", "then", "refresh", "app", "." ]
def _delayed_refresh(self): """ Give the ChromeCast time to start the app, then refresh app. """ with self._refresh_lock: if self._refresh_timer: self._refresh_timer.cancel() self._refresh_timer = threading.Timer(5, self.refresh) self._refresh_timer.start()
[ "def", "_delayed_refresh", "(", "self", ")", ":", "with", "self", ".", "_refresh_lock", ":", "if", "self", ".", "_refresh_timer", ":", "self", ".", "_refresh_timer", ".", "cancel", "(", ")", "self", ".", "_refresh_timer", "=", "threading", ".", "Timer", "(", "5", ",", "self", ".", "refresh", ")", "self", ".", "_refresh_timer", ".", "start", "(", ")" ]
https://github.com/BishopFox/rickmote/blob/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9/pychromecast/__init__.py#L159-L166
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
util/log_analyzer.py
python
_get_time
(log)
return datetime.strptime(tstamp, "%Y-%m-%d %H:%M:%S")
Parse timestamp from log line
Parse timestamp from log line
[ "Parse", "timestamp", "from", "log", "line" ]
def _get_time(log): """Parse timestamp from log line""" tstamp = log[:19] return datetime.strptime(tstamp, "%Y-%m-%d %H:%M:%S")
[ "def", "_get_time", "(", "log", ")", ":", "tstamp", "=", "log", "[", ":", "19", "]", "return", "datetime", ".", "strptime", "(", "tstamp", ",", "\"%Y-%m-%d %H:%M:%S\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/util/log_analyzer.py#L17-L20
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
util/log_analyzer.py
python
_parse
(log, start_time)
return info
Parse logs in the format from monitor.py Args: log : String containing the logged line. start_time : Log file's starting time. Returns: Dictionary with the receiver metrics.
Parse logs in the format from monitor.py
[ "Parse", "logs", "in", "the", "format", "from", "monitor", ".", "py" ]
def _parse(log, start_time): """Parse logs in the format from monitor.py Args: log : String containing the logged line. start_time : Log file's starting time. Returns: Dictionary with the receiver metrics. """ log_time = _get_time(log) info = {'date': log_time, 'time': (log_time - start_time).total_seconds()} for entry in log[19:-1].split(";"): key, val = entry.split("=") key = key.strip() val = val.strip() if (key == "Lock"): val = "Locked" if val == "True" else "Unlocked" # categorial plot elif (key == "Level" or key == "SNR"): unit = re.sub('[0-9.-]', '', val) val = val.replace(unit, '') # The logs from the S400 could return NaN, in which case "val" is # empty here. Skip these values. if (val == ''): continue val = float(val) elif (key == "BER" or key == "Packet Errors"): val = float(val) else: raise ValueError("Unknown key") info[key] = val return info
[ "def", "_parse", "(", "log", ",", "start_time", ")", ":", "log_time", "=", "_get_time", "(", "log", ")", "info", "=", "{", "'date'", ":", "log_time", ",", "'time'", ":", "(", "log_time", "-", "start_time", ")", ".", "total_seconds", "(", ")", "}", "for", "entry", "in", "log", "[", "19", ":", "-", "1", "]", ".", "split", "(", "\";\"", ")", ":", "key", ",", "val", "=", "entry", ".", "split", "(", "\"=\"", ")", "key", "=", "key", ".", "strip", "(", ")", "val", "=", "val", ".", "strip", "(", ")", "if", "(", "key", "==", "\"Lock\"", ")", ":", "val", "=", "\"Locked\"", "if", "val", "==", "\"True\"", "else", "\"Unlocked\"", "# categorial plot", "elif", "(", "key", "==", "\"Level\"", "or", "key", "==", "\"SNR\"", ")", ":", "unit", "=", "re", ".", "sub", "(", "'[0-9.-]'", ",", "''", ",", "val", ")", "val", "=", "val", ".", "replace", "(", "unit", ",", "''", ")", "# The logs from the S400 could return NaN, in which case \"val\" is", "# empty here. Skip these values.", "if", "(", "val", "==", "''", ")", ":", "continue", "val", "=", "float", "(", "val", ")", "elif", "(", "key", "==", "\"BER\"", "or", "key", "==", "\"Packet Errors\"", ")", ":", "val", "=", "float", "(", "val", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown key\"", ")", "info", "[", "key", "]", "=", "val", "return", "info" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/util/log_analyzer.py#L23-L58
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
util/log_analyzer.py
python
_plot
(ds, ds_name)
Plot all results from list of dictionaries Args: ds : Dataset (list of dictionaries) ds_name : Dataset name
Plot all results from list of dictionaries
[ "Plot", "all", "results", "from", "list", "of", "dictionaries" ]
def _plot(ds, ds_name): """Plot all results from list of dictionaries Args: ds : Dataset (list of dictionaries) ds_name : Dataset name """ keys = set() for elem in ds: keys.update(list(ds[0].keys())) keys.remove("time") keys.remove("date") formatter = DateFormatter('%m/%d %H:%M') path = os.path.join("figs", ds_name) if not os.path.isdir(path): os.makedirs(path) for key in keys: logger.info("Plotting {}".format(key)) x = [r[key] for r in ds if key in r] t = [r["date"] for r in ds if key in r] # Add unit to y-label if (key == "SNR"): ylabel = "SNR (dB)" elif (key == "Level"): ylabel = "Signal Level" # NOTE: the SDR logs positive signal levels rather than dBm. if (all([val < 0 for val in x])): ylabel += " (dBm)" else: ylabel = key fig, ax = plt.subplots() plt.plot_date(t, x, ms=2) plt.ylabel(ylabel) plt.xlabel("Time (UTC)") # Plot BER in log scale as it is not zero throughout the acquisition if (key == "BER" and any([val > 0 for val in x])): ax.set_yscale('log') ax.xaxis.set_major_formatter(formatter) ax.xaxis.set_tick_params(rotation=30, labelsize=10) plt.tight_layout() savepath = os.path.join(path, key.replace("/", "_").lower() + ".png") plt.savefig(savepath, dpi=300) plt.close()
[ "def", "_plot", "(", "ds", ",", "ds_name", ")", ":", "keys", "=", "set", "(", ")", "for", "elem", "in", "ds", ":", "keys", ".", "update", "(", "list", "(", "ds", "[", "0", "]", ".", "keys", "(", ")", ")", ")", "keys", ".", "remove", "(", "\"time\"", ")", "keys", ".", "remove", "(", "\"date\"", ")", "formatter", "=", "DateFormatter", "(", "'%m/%d %H:%M'", ")", "path", "=", "os", ".", "path", ".", "join", "(", "\"figs\"", ",", "ds_name", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "for", "key", "in", "keys", ":", "logger", ".", "info", "(", "\"Plotting {}\"", ".", "format", "(", "key", ")", ")", "x", "=", "[", "r", "[", "key", "]", "for", "r", "in", "ds", "if", "key", "in", "r", "]", "t", "=", "[", "r", "[", "\"date\"", "]", "for", "r", "in", "ds", "if", "key", "in", "r", "]", "# Add unit to y-label", "if", "(", "key", "==", "\"SNR\"", ")", ":", "ylabel", "=", "\"SNR (dB)\"", "elif", "(", "key", "==", "\"Level\"", ")", ":", "ylabel", "=", "\"Signal Level\"", "# NOTE: the SDR logs positive signal levels rather than dBm.", "if", "(", "all", "(", "[", "val", "<", "0", "for", "val", "in", "x", "]", ")", ")", ":", "ylabel", "+=", "\" (dBm)\"", "else", ":", "ylabel", "=", "key", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", ")", "plt", ".", "plot_date", "(", "t", ",", "x", ",", "ms", "=", "2", ")", "plt", ".", "ylabel", "(", "ylabel", ")", "plt", ".", "xlabel", "(", "\"Time (UTC)\"", ")", "# Plot BER in log scale as it is not zero throughout the acquisition", "if", "(", "key", "==", "\"BER\"", "and", "any", "(", "[", "val", ">", "0", "for", "val", "in", "x", "]", ")", ")", ":", "ax", ".", "set_yscale", "(", "'log'", ")", "ax", ".", "xaxis", ".", "set_major_formatter", "(", "formatter", ")", "ax", ".", "xaxis", ".", "set_tick_params", "(", "rotation", "=", "30", ",", "labelsize", "=", "10", ")", "plt", ".", "tight_layout", "(", ")", "savepath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "key", ".", "replace", "(", "\"/\"", ",", "\"_\"", ")", ".", "lower", "(", ")", "+", "\".png\"", ")", "plt", ".", "savefig", "(", "savepath", ",", "dpi", "=", "300", ")", "plt", ".", "close", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/util/log_analyzer.py#L61-L113
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
util/log_analyzer.py
python
_analyze
(logs, ds_name)
Parse and plot receiver metrics
Parse and plot receiver metrics
[ "Parse", "and", "plot", "receiver", "metrics" ]
def _analyze(logs, ds_name): """Parse and plot receiver metrics""" start_time = _get_time(logs[0]) ds = list() for log in logs: logger.debug(log) res = _parse(log, start_time) logger.debug(res) if (res is not None): ds.append(res) _plot(ds, ds_name)
[ "def", "_analyze", "(", "logs", ",", "ds_name", ")", ":", "start_time", "=", "_get_time", "(", "logs", "[", "0", "]", ")", "ds", "=", "list", "(", ")", "for", "log", "in", "logs", ":", "logger", ".", "debug", "(", "log", ")", "res", "=", "_parse", "(", "log", ",", "start_time", ")", "logger", ".", "debug", "(", "res", ")", "if", "(", "res", "is", "not", "None", ")", ":", "ds", ".", "append", "(", "res", ")", "_plot", "(", "ds", ",", "ds_name", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/util/log_analyzer.py#L116-L126
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
doc/pandoc.py
python
convert_footnotes
(text, doc)
return "\n".join(lines)
Convert footnotes from github-flavored markdown into extended markdown The extended markdown format provides a more specific syntax for footnotes, which pandoc can process and convert into LaTeX footnotes. This function assumes each document has a unique set of footnotes, and that multiple docs can adopt the same footnote numbering. It keeps a global record of footnotes and increases the footnote number such that the concatenated text does not have duplicate footnotes.
Convert footnotes from github-flavored markdown into extended markdown
[ "Convert", "footnotes", "from", "github", "-", "flavored", "markdown", "into", "extended", "markdown" ]
def convert_footnotes(text, doc): """Convert footnotes from github-flavored markdown into extended markdown The extended markdown format provides a more specific syntax for footnotes, which pandoc can process and convert into LaTeX footnotes. This function assumes each document has a unique set of footnotes, and that multiple docs can adopt the same footnote numbering. It keeps a global record of footnotes and increases the footnote number such that the concatenated text does not have duplicate footnotes. """ lines = text.splitlines() footnote = None for i, line in enumerate(lines): if "<sup>" in line: footnote = re.search(r"<sup>(.*?)</sup>", line).group(1) if doc not in footnote_map: footnote_map[doc] = {} # Assign a global footnote number if footnote in footnote_map[doc]: i_footnote = footnote_map[doc][footnote]['idx'] else: i_footnote = sum([len(x) for x in footnote_map.values()]) + 1 footnote_map[doc][footnote] = { 'idx': i_footnote, 'ref_missing': True } if footnote_map[doc][footnote]['ref_missing']: # Footnote reference (without colon) lines[i] = line.replace("<sup>" + footnote + "</sup>", "[^{}]".format(i_footnote)) footnote_map[doc][footnote]['ref_missing'] = False else: # Footnote definition (with colon) lines[i] = line.replace("<sup>" + footnote + "</sup>", "[^{}]:".format(i_footnote)) return "\n".join(lines)
[ "def", "convert_footnotes", "(", "text", ",", "doc", ")", ":", "lines", "=", "text", ".", "splitlines", "(", ")", "footnote", "=", "None", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "if", "\"<sup>\"", "in", "line", ":", "footnote", "=", "re", ".", "search", "(", "r\"<sup>(.*?)</sup>\"", ",", "line", ")", ".", "group", "(", "1", ")", "if", "doc", "not", "in", "footnote_map", ":", "footnote_map", "[", "doc", "]", "=", "{", "}", "# Assign a global footnote number", "if", "footnote", "in", "footnote_map", "[", "doc", "]", ":", "i_footnote", "=", "footnote_map", "[", "doc", "]", "[", "footnote", "]", "[", "'idx'", "]", "else", ":", "i_footnote", "=", "sum", "(", "[", "len", "(", "x", ")", "for", "x", "in", "footnote_map", ".", "values", "(", ")", "]", ")", "+", "1", "footnote_map", "[", "doc", "]", "[", "footnote", "]", "=", "{", "'idx'", ":", "i_footnote", ",", "'ref_missing'", ":", "True", "}", "if", "footnote_map", "[", "doc", "]", "[", "footnote", "]", "[", "'ref_missing'", "]", ":", "# Footnote reference (without colon)", "lines", "[", "i", "]", "=", "line", ".", "replace", "(", "\"<sup>\"", "+", "footnote", "+", "\"</sup>\"", ",", "\"[^{}]\"", ".", "format", "(", "i_footnote", ")", ")", "footnote_map", "[", "doc", "]", "[", "footnote", "]", "[", "'ref_missing'", "]", "=", "False", "else", ":", "# Footnote definition (with colon)", "lines", "[", "i", "]", "=", "line", ".", "replace", "(", "\"<sup>\"", "+", "footnote", "+", "\"</sup>\"", ",", "\"[^{}]:\"", ".", "format", "(", "i_footnote", ")", ")", "return", "\"\\n\"", ".", "join", "(", "lines", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/doc/pandoc.py#L10-L51
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
doc/pandoc.py
python
remove_yaml_front_matter
(text)
return text
Remove the YAML front matter of a Markdown document
Remove the YAML front matter of a Markdown document
[ "Remove", "the", "YAML", "front", "matter", "of", "a", "Markdown", "document" ]
def remove_yaml_front_matter(text): """Remove the YAML front matter of a Markdown document""" if text[0:4] == "---\n": # Find where the front matter ends lines = text.splitlines() i_end = 1 while (i_end < 10): # front matter should use less than 10 lines if lines[i_end] == "---": break i_end += 1 assert (i_end < 10), "Failed to find YAML front matter closure" # Remove also the extra line break after the front matter if (lines[i_end + 1] == ""): i_end += 1 text = "\n".join(lines[(i_end + 1):]) return text
[ "def", "remove_yaml_front_matter", "(", "text", ")", ":", "if", "text", "[", "0", ":", "4", "]", "==", "\"---\\n\"", ":", "# Find where the front matter ends", "lines", "=", "text", ".", "splitlines", "(", ")", "i_end", "=", "1", "while", "(", "i_end", "<", "10", ")", ":", "# front matter should use less than 10 lines", "if", "lines", "[", "i_end", "]", "==", "\"---\"", ":", "break", "i_end", "+=", "1", "assert", "(", "i_end", "<", "10", ")", ",", "\"Failed to find YAML front matter closure\"", "# Remove also the extra line break after the front matter", "if", "(", "lines", "[", "i_end", "+", "1", "]", "==", "\"\"", ")", ":", "i_end", "+=", "1", "text", "=", "\"\\n\"", ".", "join", "(", "lines", "[", "(", "i_end", "+", "1", ")", ":", "]", ")", "return", "text" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/doc/pandoc.py#L54-L72
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
doc/pandoc.py
python
fix_links
(concat_text, docs, title_map, absent_docs)
return "\n".join(lines)
Change document links to anchor links on the concatenated text The original Markdown docs are linked to each other based on file names. However, once they are concatenated, the original file links do not work anymore. This function fixes the problem by changing the file links into the corresponding in-document anchor links, based on the document's title heading. The other problem is that not all markdown docs are included on the compiled pdf version. This function removes links to the docs are not present in the concatenated text.
Change document links to anchor links on the concatenated text
[ "Change", "document", "links", "to", "anchor", "links", "on", "the", "concatenated", "text" ]
def fix_links(concat_text, docs, title_map, absent_docs): """Change document links to anchor links on the concatenated text The original Markdown docs are linked to each other based on file names. However, once they are concatenated, the original file links do not work anymore. This function fixes the problem by changing the file links into the corresponding in-document anchor links, based on the document's title heading. The other problem is that not all markdown docs are included on the compiled pdf version. This function removes links to the docs are not present in the concatenated text. """ # Replace all document links with the corresponding anchor link for doc in docs: # Convert title to the corresponding markdown anchor link anchor_link = title_map[doc].lower().replace(" ", "-") # Replace direct links original_link = "({})".format(doc) new_link = "(#{})".format(anchor_link) concat_text = concat_text.replace(original_link, new_link) # Fix links pointing to a particular subsection concat_text = concat_text.replace("({}#".format(doc), "(#") # Replace links to absent docs lines = concat_text.splitlines() for doc in absent_docs: original_link = "({})".format(doc) for i, line in enumerate(lines): if original_link in line: match = re.search(r"\[(.*?)\]\(" + doc + r"\)", line) lines[i] = line.replace(match.group(0), match.group(1)) return "\n".join(lines)
[ "def", "fix_links", "(", "concat_text", ",", "docs", ",", "title_map", ",", "absent_docs", ")", ":", "# Replace all document links with the corresponding anchor link", "for", "doc", "in", "docs", ":", "# Convert title to the corresponding markdown anchor link", "anchor_link", "=", "title_map", "[", "doc", "]", ".", "lower", "(", ")", ".", "replace", "(", "\" \"", ",", "\"-\"", ")", "# Replace direct links", "original_link", "=", "\"({})\"", ".", "format", "(", "doc", ")", "new_link", "=", "\"(#{})\"", ".", "format", "(", "anchor_link", ")", "concat_text", "=", "concat_text", ".", "replace", "(", "original_link", ",", "new_link", ")", "# Fix links pointing to a particular subsection", "concat_text", "=", "concat_text", ".", "replace", "(", "\"({}#\"", ".", "format", "(", "doc", ")", ",", "\"(#\"", ")", "# Replace links to absent docs", "lines", "=", "concat_text", ".", "splitlines", "(", ")", "for", "doc", "in", "absent_docs", ":", "original_link", "=", "\"({})\"", ".", "format", "(", "doc", ")", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "if", "original_link", "in", "line", ":", "match", "=", "re", ".", "search", "(", "r\"\\[(.*?)\\]\\(\"", "+", "doc", "+", "r\"\\)\"", ",", "line", ")", "lines", "[", "i", "]", "=", "line", ".", "replace", "(", "match", ".", "group", "(", "0", ")", ",", "match", ".", "group", "(", "1", ")", ")", "return", "\"\\n\"", ".", "join", "(", "lines", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/doc/pandoc.py#L75-L111
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
_get_iptables_rules
(net_if)
return rules
Get iptables rules that are specifically applied to a target interface Args: net_if : network interface name Returns: list of dictionaries with information of the individual matched rules
Get iptables rules that are specifically applied to a target interface
[ "Get", "iptables", "rules", "that", "are", "specifically", "applied", "to", "a", "target", "interface" ]
def _get_iptables_rules(net_if): """Get iptables rules that are specifically applied to a target interface Args: net_if : network interface name Returns: list of dictionaries with information of the individual matched rules """ # Unfortunately, root privileges are required to read the current firewall # rules. Hence, we can't read the current rules without eventually asking # the root password in dry-run mode. As a workaround, return an empty list # as if the rule was not set yet. if (runner.dry): return [] # Get rules cmd = ["iptables", "-L", "-v", "--line-numbers"] res = runner.run(cmd, root=True, capture_output=True).stdout # Parse header1 = "" header2 = "" rules = list() for line in res.splitlines(): if ("Chain INPUT" in line.decode()): header1 = line.decode() if ("destination" in line.decode()): header2 = line.decode() if (net_if in line.decode()): rules.append({ 'rule': line.decode().split(), 'header1': header1, 'header2': header2 }) return rules
[ "def", "_get_iptables_rules", "(", "net_if", ")", ":", "# Unfortunately, root privileges are required to read the current firewall", "# rules. Hence, we can't read the current rules without eventually asking", "# the root password in dry-run mode. As a workaround, return an empty list", "# as if the rule was not set yet.", "if", "(", "runner", ".", "dry", ")", ":", "return", "[", "]", "# Get rules", "cmd", "=", "[", "\"iptables\"", ",", "\"-L\"", ",", "\"-v\"", ",", "\"--line-numbers\"", "]", "res", "=", "runner", ".", "run", "(", "cmd", ",", "root", "=", "True", ",", "capture_output", "=", "True", ")", ".", "stdout", "# Parse", "header1", "=", "\"\"", "header2", "=", "\"\"", "rules", "=", "list", "(", ")", "for", "line", "in", "res", ".", "splitlines", "(", ")", ":", "if", "(", "\"Chain INPUT\"", "in", "line", ".", "decode", "(", ")", ")", ":", "header1", "=", "line", ".", "decode", "(", ")", "if", "(", "\"destination\"", "in", "line", ".", "decode", "(", ")", ")", ":", "header2", "=", "line", ".", "decode", "(", ")", "if", "(", "net_if", "in", "line", ".", "decode", "(", ")", ")", ":", "rules", ".", "append", "(", "{", "'rule'", ":", "line", ".", "decode", "(", ")", ".", "split", "(", ")", ",", "'header1'", ":", "header1", ",", "'header2'", ":", "header2", "}", ")", "return", "rules" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L11-L50
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
_is_iptables_igmp_rule_set
(net_if, cmd)
return False
Check if an iptables rule for IGMP is already configured Args: net_if : network interface name cmd : list with iptables command Returns: True if rule is already set, False otherwise.
Check if an iptables rule for IGMP is already configured
[ "Check", "if", "an", "iptables", "rule", "for", "IGMP", "is", "already", "configured" ]
def _is_iptables_igmp_rule_set(net_if, cmd): """Check if an iptables rule for IGMP is already configured Args: net_if : network interface name cmd : list with iptables command Returns: True if rule is already set, False otherwise. """ assert (cmd[0] != "sudo") for rule in _get_iptables_rules(net_if): if (rule['rule'][3] == "ACCEPT" and rule['rule'][6] == cmd[6] and rule['rule'][4] == "igmp"): print("\nFirewall rule for IGMP already configured\n") print(rule['header1']) print(rule['header2']) print(" ".join(rule['rule'])) print("\nSkipping...") return True return False
[ "def", "_is_iptables_igmp_rule_set", "(", "net_if", ",", "cmd", ")", ":", "assert", "(", "cmd", "[", "0", "]", "!=", "\"sudo\"", ")", "for", "rule", "in", "_get_iptables_rules", "(", "net_if", ")", ":", "if", "(", "rule", "[", "'rule'", "]", "[", "3", "]", "==", "\"ACCEPT\"", "and", "rule", "[", "'rule'", "]", "[", "6", "]", "==", "cmd", "[", "6", "]", "and", "rule", "[", "'rule'", "]", "[", "4", "]", "==", "\"igmp\"", ")", ":", "print", "(", "\"\\nFirewall rule for IGMP already configured\\n\"", ")", "print", "(", "rule", "[", "'header1'", "]", ")", "print", "(", "rule", "[", "'header2'", "]", ")", "print", "(", "\" \"", ".", "join", "(", "rule", "[", "'rule'", "]", ")", ")", "print", "(", "\"\\nSkipping...\"", ")", "return", "True", "return", "False" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L53-L75
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
_is_iptables_udp_rule_set
(net_if, cmd)
return False
Check if an iptables rule for UDP is already configured Args: net_if : network interface name cmd : list with iptables command Returns: True if rule is already set, False otherwise.
Check if an iptables rule for UDP is already configured
[ "Check", "if", "an", "iptables", "rule", "for", "UDP", "is", "already", "configured" ]
def _is_iptables_udp_rule_set(net_if, cmd): """Check if an iptables rule for UDP is already configured Args: net_if : network interface name cmd : list with iptables command Returns: True if rule is already set, False otherwise. """ assert (cmd[0] != "sudo") for rule in _get_iptables_rules(net_if): if (rule['rule'][3] == "ACCEPT" and rule['rule'][6] == cmd[6] and rule['rule'][4] == "udp" and rule['rule'][12] == cmd[10]): print("\nFirewall rule already configured\n") print(rule['header1']) print(rule['header2']) print(" ".join(rule['rule'])) print("\nSkipping...") return True return False
[ "def", "_is_iptables_udp_rule_set", "(", "net_if", ",", "cmd", ")", ":", "assert", "(", "cmd", "[", "0", "]", "!=", "\"sudo\"", ")", "for", "rule", "in", "_get_iptables_rules", "(", "net_if", ")", ":", "if", "(", "rule", "[", "'rule'", "]", "[", "3", "]", "==", "\"ACCEPT\"", "and", "rule", "[", "'rule'", "]", "[", "6", "]", "==", "cmd", "[", "6", "]", "and", "rule", "[", "'rule'", "]", "[", "4", "]", "==", "\"udp\"", "and", "rule", "[", "'rule'", "]", "[", "12", "]", "==", "cmd", "[", "10", "]", ")", ":", "print", "(", "\"\\nFirewall rule already configured\\n\"", ")", "print", "(", "rule", "[", "'header1'", "]", ")", "print", "(", "rule", "[", "'header2'", "]", ")", "print", "(", "\" \"", ".", "join", "(", "rule", "[", "'rule'", "]", ")", ")", "print", "(", "\"\\nSkipping...\"", ")", "return", "True", "return", "False" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L78-L100
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
_add_iptables_rule
(net_if, cmd)
Add iptables rule Args: net_if : network interface name cmd : list with iptables command
Add iptables rule
[ "Add", "iptables", "rule" ]
def _add_iptables_rule(net_if, cmd): """Add iptables rule Args: net_if : network interface name cmd : list with iptables command """ assert (cmd[0] != "sudo") # Set up the iptables rules runner.run(cmd, root=True) for rule in _get_iptables_rules(net_if): print_rule = False if (rule['rule'][3] == "ACCEPT" and rule['rule'][6] == cmd[6] and rule['rule'][4] == cmd[4]): if (cmd[4] == "igmp"): print_rule = True elif (cmd[4] == "udp" and rule['rule'][12] == cmd[10]): print_rule = True if (print_rule): print("Added iptables rule:\n") print(rule['header1']) print(rule['header2']) print(" ".join(rule['rule']) + "\n")
[ "def", "_add_iptables_rule", "(", "net_if", ",", "cmd", ")", ":", "assert", "(", "cmd", "[", "0", "]", "!=", "\"sudo\"", ")", "# Set up the iptables rules", "runner", ".", "run", "(", "cmd", ",", "root", "=", "True", ")", "for", "rule", "in", "_get_iptables_rules", "(", "net_if", ")", ":", "print_rule", "=", "False", "if", "(", "rule", "[", "'rule'", "]", "[", "3", "]", "==", "\"ACCEPT\"", "and", "rule", "[", "'rule'", "]", "[", "6", "]", "==", "cmd", "[", "6", "]", "and", "rule", "[", "'rule'", "]", "[", "4", "]", "==", "cmd", "[", "4", "]", ")", ":", "if", "(", "cmd", "[", "4", "]", "==", "\"igmp\"", ")", ":", "print_rule", "=", "True", "elif", "(", "cmd", "[", "4", "]", "==", "\"udp\"", "and", "rule", "[", "'rule'", "]", "[", "12", "]", "==", "cmd", "[", "10", "]", ")", ":", "print_rule", "=", "True", "if", "(", "print_rule", ")", ":", "print", "(", "\"Added iptables rule:\\n\"", ")", "print", "(", "rule", "[", "'header1'", "]", ")", "print", "(", "rule", "[", "'header2'", "]", ")", "print", "(", "\" \"", ".", "join", "(", "rule", "[", "'rule'", "]", ")", "+", "\"\\n\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L103-L130
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
_configure_iptables
(net_if, ports, igmp=False, prompt=True)
Configure iptables rules to accept blocksat traffic on a DVB-S2 interface Args: net_if : DVB network interface name ports : ports used for blocks traffic and API traffic igmp : Whether or not to configure rule to accept IGMP queries prompt : Ask yes/no before applying any changes
Configure iptables rules to accept blocksat traffic on a DVB-S2 interface
[ "Configure", "iptables", "rules", "to", "accept", "blocksat", "traffic", "on", "a", "DVB", "-", "S2", "interface" ]
def _configure_iptables(net_if, ports, igmp=False, prompt=True): """Configure iptables rules to accept blocksat traffic on a DVB-S2 interface Args: net_if : DVB network interface name ports : ports used for blocks traffic and API traffic igmp : Whether or not to configure rule to accept IGMP queries prompt : Ask yes/no before applying any changes """ cmd = [ "iptables", "-I", "INPUT", "-p", "udp", "-i", net_if, "--match", "multiport", "--dports", ",".join(ports), "-j", "ACCEPT", ] util.fill_print( "A firewall rule is required to accept Blocksat traffic arriving " + "through interface {} towards UDP ports {}.".format( net_if, ",".join(ports))) if (runner.dry): util.fill_print("The following command would be executed:") if (not _is_iptables_udp_rule_set(net_if, cmd)): if (runner.dry or (not prompt) or util.ask_yes_or_no( "Add the corresponding ACCEPT firewall rule?")): _add_iptables_rule(net_if, cmd) else: print("\nFirewall configuration cancelled") # We're done, unless we also need to configure an IGMP rule if (not igmp): return # IGMP rule supports standalone DVB receivers. The host in this case will # need to periodically send IGMP membership reports in order for upstream # switches between itself and the DVB receiver to continue delivering the # multicast-addressed traffic. This overcomes the scenario where group # membership timeouts are implemented by the intermediate switches. cmd = [ "iptables", "-I", "INPUT", "-p", "igmp", "-i", net_if, "-j", "ACCEPT", ] print() util.fill_print( "A firewall rule is required to accept IGMP queries arriving from the " "standalone DVB-S2 receiver on interface {}.".format(net_if)) if (runner.dry): util.fill_print("The following command would be executed:") if (not _is_iptables_igmp_rule_set(net_if, cmd)): if (runner.dry or (not prompt) or util.ask_yes_or_no( "Add the corresponding ACCEPT firewall rule?")): _add_iptables_rule(net_if, cmd) else: print("\nIGMP firewall rule cancelled")
[ "def", "_configure_iptables", "(", "net_if", ",", "ports", ",", "igmp", "=", "False", ",", "prompt", "=", "True", ")", ":", "cmd", "=", "[", "\"iptables\"", ",", "\"-I\"", ",", "\"INPUT\"", ",", "\"-p\"", ",", "\"udp\"", ",", "\"-i\"", ",", "net_if", ",", "\"--match\"", ",", "\"multiport\"", ",", "\"--dports\"", ",", "\",\"", ".", "join", "(", "ports", ")", ",", "\"-j\"", ",", "\"ACCEPT\"", ",", "]", "util", ".", "fill_print", "(", "\"A firewall rule is required to accept Blocksat traffic arriving \"", "+", "\"through interface {} towards UDP ports {}.\"", ".", "format", "(", "net_if", ",", "\",\"", ".", "join", "(", "ports", ")", ")", ")", "if", "(", "runner", ".", "dry", ")", ":", "util", ".", "fill_print", "(", "\"The following command would be executed:\"", ")", "if", "(", "not", "_is_iptables_udp_rule_set", "(", "net_if", ",", "cmd", ")", ")", ":", "if", "(", "runner", ".", "dry", "or", "(", "not", "prompt", ")", "or", "util", ".", "ask_yes_or_no", "(", "\"Add the corresponding ACCEPT firewall rule?\"", ")", ")", ":", "_add_iptables_rule", "(", "net_if", ",", "cmd", ")", "else", ":", "print", "(", "\"\\nFirewall configuration cancelled\"", ")", "# We're done, unless we also need to configure an IGMP rule", "if", "(", "not", "igmp", ")", ":", "return", "# IGMP rule supports standalone DVB receivers. The host in this case will", "# need to periodically send IGMP membership reports in order for upstream", "# switches between itself and the DVB receiver to continue delivering the", "# multicast-addressed traffic. This overcomes the scenario where group", "# membership timeouts are implemented by the intermediate switches.", "cmd", "=", "[", "\"iptables\"", ",", "\"-I\"", ",", "\"INPUT\"", ",", "\"-p\"", ",", "\"igmp\"", ",", "\"-i\"", ",", "net_if", ",", "\"-j\"", ",", "\"ACCEPT\"", ",", "]", "print", "(", ")", "util", ".", "fill_print", "(", "\"A firewall rule is required to accept IGMP queries arriving from the \"", "\"standalone DVB-S2 receiver on interface {}.\"", ".", "format", "(", "net_if", ")", ")", "if", "(", "runner", ".", "dry", ")", ":", "util", ".", "fill_print", "(", "\"The following command would be executed:\"", ")", "if", "(", "not", "_is_iptables_igmp_rule_set", "(", "net_if", ",", "cmd", ")", ")", ":", "if", "(", "runner", ".", "dry", "or", "(", "not", "prompt", ")", "or", "util", ".", "ask_yes_or_no", "(", "\"Add the corresponding ACCEPT firewall rule?\"", ")", ")", ":", "_add_iptables_rule", "(", "net_if", ",", "cmd", ")", "else", ":", "print", "(", "\"\\nIGMP firewall rule cancelled\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L133-L209
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
is_firewalld
()
return (res1.returncode == 0)
Check if the firewall is based on firewalld
Check if the firewall is based on firewalld
[ "Check", "if", "the", "firewall", "is", "based", "on", "firewalld" ]
def is_firewalld(): """Check if the firewall is based on firewalld""" if (which('firewall-cmd') is None): return False if (which('systemctl') is None): # Can't check whether firewalld is running return False # Run the following commands even in dry-run mode res1 = runner.run(['systemctl', 'is-active', '--quiet', 'firewalld'], nodry=True, nocheck=True) res2 = runner.run(['systemctl', 'is-active', '--quiet', 'iptables'], nodry=True, nocheck=True) # If running (active), 'is-active' returns 0 if (res1.returncode == 0 and res2.returncode == 0): raise ValueError( "Failed to detect firewall system (firewalld or iptables)") return (res1.returncode == 0)
[ "def", "is_firewalld", "(", ")", ":", "if", "(", "which", "(", "'firewall-cmd'", ")", "is", "None", ")", ":", "return", "False", "if", "(", "which", "(", "'systemctl'", ")", "is", "None", ")", ":", "# Can't check whether firewalld is running", "return", "False", "# Run the following commands even in dry-run mode", "res1", "=", "runner", ".", "run", "(", "[", "'systemctl'", ",", "'is-active'", ",", "'--quiet'", ",", "'firewalld'", "]", ",", "nodry", "=", "True", ",", "nocheck", "=", "True", ")", "res2", "=", "runner", ".", "run", "(", "[", "'systemctl'", ",", "'is-active'", ",", "'--quiet'", ",", "'iptables'", "]", ",", "nodry", "=", "True", ",", "nocheck", "=", "True", ")", "# If running (active), 'is-active' returns 0", "if", "(", "res1", ".", "returncode", "==", "0", "and", "res2", ".", "returncode", "==", "0", ")", ":", "raise", "ValueError", "(", "\"Failed to detect firewall system (firewalld or iptables)\"", ")", "return", "(", "res1", ".", "returncode", "==", "0", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L212-L234
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
_configure_firewalld
(net_if, ports, src_ip, igmp, prompt)
Configure firewalld for blocksat and IGMP traffic Add one rich rule for blocksat traffic coming specifically from the satellite of choice (corresponding to the given source IP) and another rich rule (if necessary) for IGMP traffic. NOTE: unlike the iptables configuration, the current firewalld configuration disregards the network interface. The alternative to consider the interface is to use firewalld zones. However, because the network interface may not be dedicated to DVB-S2 traffic (e.g., when using a standalone receiver), it can be undesirable to assign the interface receiving satellite traffic to a dedicated zone just for blocksat. In contrast, the rich rule approach is more generic and works for all types of receivers.
Configure firewalld for blocksat and IGMP traffic
[ "Configure", "firewalld", "for", "blocksat", "and", "IGMP", "traffic" ]
def _configure_firewalld(net_if, ports, src_ip, igmp, prompt): """Configure firewalld for blocksat and IGMP traffic Add one rich rule for blocksat traffic coming specifically from the satellite of choice (corresponding to the given source IP) and another rich rule (if necessary) for IGMP traffic. NOTE: unlike the iptables configuration, the current firewalld configuration disregards the network interface. The alternative to consider the interface is to use firewalld zones. However, because the network interface may not be dedicated to DVB-S2 traffic (e.g., when using a standalone receiver), it can be undesirable to assign the interface receiving satellite traffic to a dedicated zone just for blocksat. In contrast, the rich rule approach is more generic and works for all types of receivers. """ if len(ports) > 1: portrange = "{}-{}".format(min(ports), max(ports)) else: portrange = ports util.fill_print( "- Configure the firewall to accept Blocksat traffic arriving " + "from {} towards address {} on UDP ports {}:\n".format( src_ip, defs.mcast_ip, portrange)) if (not runner.dry and prompt): if (not util.ask_yes_or_no("Add firewalld rule?")): print("\nFirewall configuration cancelled") return rich_rule = ("rule " "family=ipv4 " "source address={} " "destination address={}/32 " "port port={} protocol=udp accept".format( src_ip, defs.mcast_ip, portrange)) runner.run(['firewall-cmd', '--add-rich-rule', "{}".format(rich_rule)], root=True) if (runner.dry): print() util.fill_print( "NOTE: Add \"--permanent\" to make it persistent. In this case, " "remember to reload firewalld afterwards.") # We're done, unless we also need to configure an IGMP rule if (not igmp): return util.fill_print( "- Allow IGMP packets. This is necessary when using a standalone " "DVB-S2 receiver connected through a switch:\n") if (not runner.dry and prompt): if (not util.ask_yes_or_no("Enable IGMP on the firewall?")): print("\nFirewall configuration cancelled") return runner.run(['firewall-cmd', '--add-protocol=igmp'], root=True) print()
[ "def", "_configure_firewalld", "(", "net_if", ",", "ports", ",", "src_ip", ",", "igmp", ",", "prompt", ")", ":", "if", "len", "(", "ports", ")", ">", "1", ":", "portrange", "=", "\"{}-{}\"", ".", "format", "(", "min", "(", "ports", ")", ",", "max", "(", "ports", ")", ")", "else", ":", "portrange", "=", "ports", "util", ".", "fill_print", "(", "\"- Configure the firewall to accept Blocksat traffic arriving \"", "+", "\"from {} towards address {} on UDP ports {}:\\n\"", ".", "format", "(", "src_ip", ",", "defs", ".", "mcast_ip", ",", "portrange", ")", ")", "if", "(", "not", "runner", ".", "dry", "and", "prompt", ")", ":", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"Add firewalld rule?\"", ")", ")", ":", "print", "(", "\"\\nFirewall configuration cancelled\"", ")", "return", "rich_rule", "=", "(", "\"rule \"", "\"family=ipv4 \"", "\"source address={} \"", "\"destination address={}/32 \"", "\"port port={} protocol=udp accept\"", ".", "format", "(", "src_ip", ",", "defs", ".", "mcast_ip", ",", "portrange", ")", ")", "runner", ".", "run", "(", "[", "'firewall-cmd'", ",", "'--add-rich-rule'", ",", "\"{}\"", ".", "format", "(", "rich_rule", ")", "]", ",", "root", "=", "True", ")", "if", "(", "runner", ".", "dry", ")", ":", "print", "(", ")", "util", ".", "fill_print", "(", "\"NOTE: Add \\\"--permanent\\\" to make it persistent. In this case, \"", "\"remember to reload firewalld afterwards.\"", ")", "# We're done, unless we also need to configure an IGMP rule", "if", "(", "not", "igmp", ")", ":", "return", "util", ".", "fill_print", "(", "\"- Allow IGMP packets. This is necessary when using a standalone \"", "\"DVB-S2 receiver connected through a switch:\\n\"", ")", "if", "(", "not", "runner", ".", "dry", "and", "prompt", ")", ":", "if", "(", "not", "util", ".", "ask_yes_or_no", "(", "\"Enable IGMP on the firewall?\"", ")", ")", ":", "print", "(", "\"\\nFirewall configuration cancelled\"", ")", "return", "runner", ".", "run", "(", "[", "'firewall-cmd'", ",", "'--add-protocol=igmp'", "]", ",", "root", "=", "True", ")", "print", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L237-L299
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
configure
(net_ifs, ports, src_ip, igmp=False, prompt=True, dry=False)
Configure firewallrules to accept blocksat traffic via DVB interface Args: net_ifs : List of DVB network interface names ports : UDP ports used by satellite traffic src_ip : Source IP to whitelist (unique to each satellite) igmp : Whether or not to configure rule to accept IGMP queries prompt : Prompt user to accept configurations before executing them dry : Dry run mode
Configure firewallrules to accept blocksat traffic via DVB interface
[ "Configure", "firewallrules", "to", "accept", "blocksat", "traffic", "via", "DVB", "interface" ]
def configure(net_ifs, ports, src_ip, igmp=False, prompt=True, dry=False): """Configure firewallrules to accept blocksat traffic via DVB interface Args: net_ifs : List of DVB network interface names ports : UDP ports used by satellite traffic src_ip : Source IP to whitelist (unique to each satellite) igmp : Whether or not to configure rule to accept IGMP queries prompt : Prompt user to accept configurations before executing them dry : Dry run mode """ assert (isinstance(net_ifs, list)) runner.set_dry(dry) util.print_header("Firewall Rules") for i, net_if in enumerate(net_ifs): if (is_firewalld()): _configure_firewalld(net_if, ports, src_ip, igmp, prompt) else: _configure_iptables(net_if, ports, igmp, prompt) if (i < len(net_ifs) - 1): print("")
[ "def", "configure", "(", "net_ifs", ",", "ports", ",", "src_ip", ",", "igmp", "=", "False", ",", "prompt", "=", "True", ",", "dry", "=", "False", ")", ":", "assert", "(", "isinstance", "(", "net_ifs", ",", "list", ")", ")", "runner", ".", "set_dry", "(", "dry", ")", "util", ".", "print_header", "(", "\"Firewall Rules\"", ")", "for", "i", ",", "net_if", "in", "enumerate", "(", "net_ifs", ")", ":", "if", "(", "is_firewalld", "(", ")", ")", ":", "_configure_firewalld", "(", "net_if", ",", "ports", ",", "src_ip", ",", "igmp", ",", "prompt", ")", "else", ":", "_configure_iptables", "(", "net_if", ",", "ports", ",", "igmp", ",", "prompt", ")", "if", "(", "i", "<", "len", "(", "net_ifs", ")", "-", "1", ")", ":", "print", "(", "\"\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L302-L325
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
subparser
(subparsers)
return p
Parser for firewall command
Parser for firewall command
[ "Parser", "for", "firewall", "command" ]
def subparser(subparsers): """Parser for firewall command""" p = subparsers.add_parser('firewall', description="Set firewall rules", help='Set firewall rules', formatter_class=ArgumentDefaultsHelpFormatter) p.add_argument('-i', '--interface', required=True, help='Network interface') p.add_argument( '--standalone', default=False, action='store_true', help='Apply configurations for a standalone DVB-S2 receiver') p.add_argument('-y', '--yes', default=False, action='store_true', help="Default to answering Yes to configuration prompts") p.add_argument("--dry-run", action='store_true', default=False, help="Print all commands but do not execute them") p.set_defaults(func=firewall_subcommand) return p
[ "def", "subparser", "(", "subparsers", ")", ":", "p", "=", "subparsers", ".", "add_parser", "(", "'firewall'", ",", "description", "=", "\"Set firewall rules\"", ",", "help", "=", "'Set firewall rules'", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "p", ".", "add_argument", "(", "'-i'", ",", "'--interface'", ",", "required", "=", "True", ",", "help", "=", "'Network interface'", ")", "p", ".", "add_argument", "(", "'--standalone'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'Apply configurations for a standalone DVB-S2 receiver'", ")", "p", ".", "add_argument", "(", "'-y'", ",", "'--yes'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Default to answering Yes to configuration prompts\"", ")", "p", ".", "add_argument", "(", "\"--dry-run\"", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "\"Print all commands but do not execute them\"", ")", "p", ".", "set_defaults", "(", "func", "=", "firewall_subcommand", ")", "return", "p" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L328-L353
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/firewall.py
python
firewall_subcommand
(args)
Call function that sets firewall rules Handles the firewall subcommand
Call function that sets firewall rules
[ "Call", "function", "that", "sets", "firewall", "rules" ]
def firewall_subcommand(args): """Call function that sets firewall rules Handles the firewall subcommand """ user_info = config.read_cfg_file(args.cfg, args.cfg_dir) if (user_info is None): return configure([args.interface], defs.src_ports, user_info['sat']['ip'], igmp=args.standalone, prompt=(not args.yes), dry=args.dry_run)
[ "def", "firewall_subcommand", "(", "args", ")", ":", "user_info", "=", "config", ".", "read_cfg_file", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ")", "if", "(", "user_info", "is", "None", ")", ":", "return", "configure", "(", "[", "args", ".", "interface", "]", ",", "defs", ".", "src_ports", ",", "user_info", "[", "'sat'", "]", "[", "'ip'", "]", ",", "igmp", "=", "args", ".", "standalone", ",", "prompt", "=", "(", "not", "args", ".", "yes", ")", ",", "dry", "=", "args", ".", "dry_run", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/firewall.py#L356-L372
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/update.py
python
_check_pip_updates
(cfg_dir, cli_version)
Check if the CLI has updates available via pip Args: cfg_dir : Directory where the .update is located/created cli_version : Current version of the CLI
Check if the CLI has updates available via pip
[ "Check", "if", "the", "CLI", "has", "updates", "available", "via", "pip" ]
def _check_pip_updates(cfg_dir, cli_version): """Check if the CLI has updates available via pip Args: cfg_dir : Directory where the .update is located/created cli_version : Current version of the CLI """ logger.debug("Checking blocksat-cli updates") # Save the new pip verification timestamp on the cache file update_cache = UpdateCache(cfg_dir) update_cache.save() # Is blocksat-cli installed? res = subprocess.run(["pip3", "show", "blocksat-cli"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) found = (res.returncode == 0) # If the CLI was not installed via pip, don't check updates if (not found): logger.debug("Could not find blocksat-cli installed via pip3") return # Is the CLI outdated? try: outdated_list = json.loads( subprocess.check_output( ["pip3", "list", "--outdated", "--format", "json"], stderr=subprocess.DEVNULL).decode()) except subprocess.CalledProcessError: # Don't break if the command fails. It could be a problem on pip. For # example, there is a bug in which pip throws a TypeError on the "list # --outdated" command saying: '>' not supported between instances of # 'Version' and 'Version' logger.warning("Failed to check blocksat-cli updates.") return cli_outdated = False for package in outdated_list: if (package['name'] == "blocksat-cli"): cli_outdated = True # Save the available update on the cache file update_cache.save((package['version'], package['latest_version'])) logger.debug("Update available for blocksat-cli") if (not cli_outdated): logger.debug("blocksat-cli is up-to-date") # Clear a potential update flag on the cache file update_cache.save()
[ "def", "_check_pip_updates", "(", "cfg_dir", ",", "cli_version", ")", ":", "logger", ".", "debug", "(", "\"Checking blocksat-cli updates\"", ")", "# Save the new pip verification timestamp on the cache file", "update_cache", "=", "UpdateCache", "(", "cfg_dir", ")", "update_cache", ".", "save", "(", ")", "# Is blocksat-cli installed?", "res", "=", "subprocess", ".", "run", "(", "[", "\"pip3\"", ",", "\"show\"", ",", "\"blocksat-cli\"", "]", ",", "stdout", "=", "subprocess", ".", "DEVNULL", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ")", "found", "=", "(", "res", ".", "returncode", "==", "0", ")", "# If the CLI was not installed via pip, don't check updates", "if", "(", "not", "found", ")", ":", "logger", ".", "debug", "(", "\"Could not find blocksat-cli installed via pip3\"", ")", "return", "# Is the CLI outdated?", "try", ":", "outdated_list", "=", "json", ".", "loads", "(", "subprocess", ".", "check_output", "(", "[", "\"pip3\"", ",", "\"list\"", ",", "\"--outdated\"", ",", "\"--format\"", ",", "\"json\"", "]", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ")", ".", "decode", "(", ")", ")", "except", "subprocess", ".", "CalledProcessError", ":", "# Don't break if the command fails. It could be a problem on pip. For", "# example, there is a bug in which pip throws a TypeError on the \"list", "# --outdated\" command saying: '>' not supported between instances of", "# 'Version' and 'Version'", "logger", ".", "warning", "(", "\"Failed to check blocksat-cli updates.\"", ")", "return", "cli_outdated", "=", "False", "for", "package", "in", "outdated_list", ":", "if", "(", "package", "[", "'name'", "]", "==", "\"blocksat-cli\"", ")", ":", "cli_outdated", "=", "True", "# Save the available update on the cache file", "update_cache", ".", "save", "(", "(", "package", "[", "'version'", "]", ",", "package", "[", "'latest_version'", "]", ")", ")", "logger", ".", "debug", "(", "\"Update available for blocksat-cli\"", ")", "if", "(", "not", "cli_outdated", ")", ":", "logger", ".", "debug", "(", "\"blocksat-cli is up-to-date\"", ")", "# Clear a potential update flag on the cache file", "update_cache", ".", "save", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/update.py#L73-L123
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/update.py
python
check_cli_updates
(args, cli_version)
Check if the CLI has updates available Check the cache file first. If the cache is old enough, check updates through the pip interface. The cache file can be verified very quickly, whereas the verification through pip can be rather slow. Args: args : Arguments from parent argument parser cli_version : Current version of the CLI
Check if the CLI has updates available
[ "Check", "if", "the", "CLI", "has", "updates", "available" ]
def check_cli_updates(args, cli_version): """Check if the CLI has updates available Check the cache file first. If the cache is old enough, check updates through the pip interface. The cache file can be verified very quickly, whereas the verification through pip can be rather slow. Args: args : Arguments from parent argument parser cli_version : Current version of the CLI """ # If pip is not available, assume the CLI was not installed via pip if (not which("pip3")): logger.debug("pip3 unavailable") return # Create the configuration directory if it does not exist if not os.path.exists(args.cfg_dir): os.makedirs(args.cfg_dir, exist_ok=True) # Check the update cache file first update_cache = UpdateCache(args.cfg_dir) # If the cache file says there is an update available, check whether the # current version is already the updated one. If not, recommend the update. if (update_cache.has_update()): if (update_cache.new_version() > StrictVersion(cli_version)): # Not updated yet. Recommend it. update_cache.recommend_update() else: # Already updated. Clear the update flag. update_cache.save() return # If the last update verification was still recent (less than a day ago), # do not check pip. Avoid the unnecessary spawning of the pip-checking # thread. if (update_cache.data): time_since_last_check = (datetime.now() - update_cache.last_check()) if (time_since_last_check < timedelta(days=1)): logger.debug( "Last update check was less than a day ago: {}".format( str(time_since_last_check))) return # Check pip updates on a thread. This verification can be slow, so it is # better not to block. t = threading.Thread(target=_check_pip_updates, args=(args.cfg_dir, cli_version)) t.start()
[ "def", "check_cli_updates", "(", "args", ",", "cli_version", ")", ":", "# If pip is not available, assume the CLI was not installed via pip", "if", "(", "not", "which", "(", "\"pip3\"", ")", ")", ":", "logger", ".", "debug", "(", "\"pip3 unavailable\"", ")", "return", "# Create the configuration directory if it does not exist", "if", "not", "os", ".", "path", ".", "exists", "(", "args", ".", "cfg_dir", ")", ":", "os", ".", "makedirs", "(", "args", ".", "cfg_dir", ",", "exist_ok", "=", "True", ")", "# Check the update cache file first", "update_cache", "=", "UpdateCache", "(", "args", ".", "cfg_dir", ")", "# If the cache file says there is an update available, check whether the", "# current version is already the updated one. If not, recommend the update.", "if", "(", "update_cache", ".", "has_update", "(", ")", ")", ":", "if", "(", "update_cache", ".", "new_version", "(", ")", ">", "StrictVersion", "(", "cli_version", ")", ")", ":", "# Not updated yet. Recommend it.", "update_cache", ".", "recommend_update", "(", ")", "else", ":", "# Already updated. Clear the update flag.", "update_cache", ".", "save", "(", ")", "return", "# If the last update verification was still recent (less than a day ago),", "# do not check pip. Avoid the unnecessary spawning of the pip-checking", "# thread.", "if", "(", "update_cache", ".", "data", ")", ":", "time_since_last_check", "=", "(", "datetime", ".", "now", "(", ")", "-", "update_cache", ".", "last_check", "(", ")", ")", "if", "(", "time_since_last_check", "<", "timedelta", "(", "days", "=", "1", ")", ")", ":", "logger", ".", "debug", "(", "\"Last update check was less than a day ago: {}\"", ".", "format", "(", "str", "(", "time_since_last_check", ")", ")", ")", "return", "# Check pip updates on a thread. This verification can be slow, so it is", "# better not to block.", "t", "=", "threading", ".", "Thread", "(", "target", "=", "_check_pip_updates", ",", "args", "=", "(", "args", ".", "cfg_dir", ",", "cli_version", ")", ")", "t", ".", "start", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/update.py#L126-L177
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/update.py
python
UpdateCache.__init__
(self, cfg_dir)
UpdateCache constructor Args: cfg_dir : Directory where the .update is located/created
UpdateCache constructor
[ "UpdateCache", "constructor" ]
def __init__(self, cfg_dir): """UpdateCache constructor Args: cfg_dir : Directory where the .update is located/created """ super().__init__(cfg_dir, filename=".update")
[ "def", "__init__", "(", "self", ",", "cfg_dir", ")", ":", "super", "(", ")", ".", "__init__", "(", "cfg_dir", ",", "filename", "=", "\".update\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/update.py#L22-L29
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/update.py
python
UpdateCache.last_check
(self)
return datetime.strptime(self.data['last_check'], '%Y-%m-%d %H:%M:%S.%f')
Return the datetime corresponding to the last update verification
Return the datetime corresponding to the last update verification
[ "Return", "the", "datetime", "corresponding", "to", "the", "last", "update", "verification" ]
def last_check(self): """Return the datetime corresponding to the last update verification""" return datetime.strptime(self.data['last_check'], '%Y-%m-%d %H:%M:%S.%f')
[ "def", "last_check", "(", "self", ")", ":", "return", "datetime", ".", "strptime", "(", "self", ".", "data", "[", "'last_check'", "]", ",", "'%Y-%m-%d %H:%M:%S.%f'", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/update.py#L31-L34
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/update.py
python
UpdateCache.save
(self, cli_update=None)
Save information into the update cache file Args: cli_update : Version of a new CLI version available for update, if any
Save information into the update cache file
[ "Save", "information", "into", "the", "update", "cache", "file" ]
def save(self, cli_update=None): """Save information into the update cache file Args: cli_update : Version of a new CLI version available for update, if any """ self.data['last_check'] = datetime.now().strftime( '%Y-%m-%d %H:%M:%S.%f') self.data['cli_update'] = cli_update super().save()
[ "def", "save", "(", "self", ",", "cli_update", "=", "None", ")", ":", "self", ".", "data", "[", "'last_check'", "]", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S.%f'", ")", "self", ".", "data", "[", "'cli_update'", "]", "=", "cli_update", "super", "(", ")", ".", "save", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/update.py#L36-L47
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/update.py
python
UpdateCache.has_update
(self)
return 'cli_update' in self.data and \ self.data['cli_update'] is not None
Returns whether there is an update available for the CLI
Returns whether there is an update available for the CLI
[ "Returns", "whether", "there", "is", "an", "update", "available", "for", "the", "CLI" ]
def has_update(self): """Returns whether there is an update available for the CLI""" return 'cli_update' in self.data and \ self.data['cli_update'] is not None
[ "def", "has_update", "(", "self", ")", ":", "return", "'cli_update'", "in", "self", ".", "data", "and", "self", ".", "data", "[", "'cli_update'", "]", "is", "not", "None" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/update.py#L49-L52
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/update.py
python
UpdateCache.new_version
(self)
return StrictVersion(self.data['cli_update'][1])
Get the new version available for an update Note: This method should be called only if there is a new update, as confirmed by "has_update". Otherwise, it will throw an exception.
Get the new version available for an update
[ "Get", "the", "new", "version", "available", "for", "an", "update" ]
def new_version(self): """Get the new version available for an update Note: This method should be called only if there is a new update, as confirmed by "has_update". Otherwise, it will throw an exception. """ return StrictVersion(self.data['cli_update'][1])
[ "def", "new_version", "(", "self", ")", ":", "return", "StrictVersion", "(", "self", ".", "data", "[", "'cli_update'", "]", "[", "1", "]", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/update.py#L54-L61
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/update.py
python
UpdateCache.recommend_update
(self)
Print information regarding the recommended update
Print information regarding the recommended update
[ "Print", "information", "regarding", "the", "recommended", "update" ]
def recommend_update(self): """Print information regarding the recommended update""" if (self.data['cli_update'] is None): return print("\nUpdate available for blocksat-cli") print("Current version: {}.\nLatest version: {}.".format( self.data['cli_update'][0], self.data['cli_update'][1])) print("Please run:\n\n pip3 install blocksat-cli --upgrade\n\n")
[ "def", "recommend_update", "(", "self", ")", ":", "if", "(", "self", ".", "data", "[", "'cli_update'", "]", "is", "None", ")", ":", "return", "print", "(", "\"\\nUpdate available for blocksat-cli\"", ")", "print", "(", "\"Current version: {}.\\nLatest version: {}.\"", ".", "format", "(", "self", ".", "data", "[", "'cli_update'", "]", "[", "0", "]", ",", "self", ".", "data", "[", "'cli_update'", "]", "[", "1", "]", ")", ")", "print", "(", "\"Please run:\\n\\n pip3 install blocksat-cli --upgrade\\n\\n\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/update.py#L63-L70
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/cache.py
python
Cache.__init__
(self, cfg_dir, filename=".cache")
Cache constructor Args: cfg_dir : Directory where the .update is located/created
Cache constructor
[ "Cache", "constructor" ]
def __init__(self, cfg_dir, filename=".cache"): """Cache constructor Args: cfg_dir : Directory where the .update is located/created """ self.path = os.path.join(cfg_dir, filename) self.data = {} self.load()
[ "def", "__init__", "(", "self", ",", "cfg_dir", ",", "filename", "=", "\".cache\"", ")", ":", "self", ".", "path", "=", "os", ".", "path", ".", "join", "(", "cfg_dir", ",", "filename", ")", "self", ".", "data", "=", "{", "}", "self", ".", "load", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/cache.py#L12-L21
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/cache.py
python
Cache.load
(self)
Load data from the cache file
Load data from the cache file
[ "Load", "data", "from", "the", "cache", "file" ]
def load(self): """Load data from the cache file""" if (not os.path.exists(self.path)): return try: with open(self.path, 'r') as fd: self.data = json.load(fd) except json.decoder.JSONDecodeError: return
[ "def", "load", "(", "self", ")", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", ")", ":", "return", "try", ":", "with", "open", "(", "self", ".", "path", ",", "'r'", ")", "as", "fd", ":", "self", ".", "data", "=", "json", ".", "load", "(", "fd", ")", "except", "json", ".", "decoder", ".", "JSONDecodeError", ":", "return" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/cache.py#L23-L32
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/cache.py
python
Cache.save
(self)
Save data into the cache file Args: cli_update : Version of a new CLI version available for update, if any
Save data into the cache file
[ "Save", "data", "into", "the", "cache", "file" ]
def save(self): """Save data into the cache file Args: cli_update : Version of a new CLI version available for update, if any """ with open(self.path, 'w') as fd: json.dump(self.data, fd)
[ "def", "save", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ",", "'w'", ")", "as", "fd", ":", "json", ".", "dump", "(", "self", ".", "data", ",", "fd", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/cache.py#L34-L43
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/cache.py
python
Cache.get
(self, field)
Get using dot notation
Get using dot notation
[ "Get", "using", "dot", "notation" ]
def get(self, field): """Get using dot notation""" nested_keys = field.split('.') tmp = self.data for i, key in enumerate(nested_keys): if key not in tmp: return None if i == len(nested_keys) - 1: return tmp[key] tmp = tmp[key]
[ "def", "get", "(", "self", ",", "field", ")", ":", "nested_keys", "=", "field", ".", "split", "(", "'.'", ")", "tmp", "=", "self", ".", "data", "for", "i", ",", "key", "in", "enumerate", "(", "nested_keys", ")", ":", "if", "key", "not", "in", "tmp", ":", "return", "None", "if", "i", "==", "len", "(", "nested_keys", ")", "-", "1", ":", "return", "tmp", "[", "key", "]", "tmp", "=", "tmp", "[", "key", "]" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/cache.py#L45-L54
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/cache.py
python
Cache.set
(self, field, val, overwrite=True)
Set using dot notation
Set using dot notation
[ "Set", "using", "dot", "notation" ]
def set(self, field, val, overwrite=True): """Set using dot notation""" nested_keys = field.split('.') tmp = self.data for i, key in enumerate(nested_keys): if key not in tmp: tmp[key] = {} if i == len(nested_keys) - 1: if (key in tmp and not overwrite): return tmp[key] = val tmp = tmp[key]
[ "def", "set", "(", "self", ",", "field", ",", "val", ",", "overwrite", "=", "True", ")", ":", "nested_keys", "=", "field", ".", "split", "(", "'.'", ")", "tmp", "=", "self", ".", "data", "for", "i", ",", "key", "in", "enumerate", "(", "nested_keys", ")", ":", "if", "key", "not", "in", "tmp", ":", "tmp", "[", "key", "]", "=", "{", "}", "if", "i", "==", "len", "(", "nested_keys", ")", "-", "1", ":", "if", "(", "key", "in", "tmp", "and", "not", "overwrite", ")", ":", "return", "tmp", "[", "key", "]", "=", "val", "tmp", "=", "tmp", "[", "key", "]" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/cache.py#L56-L67
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
typed_input
(msg, hint=None, in_type=int, default=None)
return res
Ask for user input of a specific type
Ask for user input of a specific type
[ "Ask", "for", "user", "input", "of", "a", "specific", "type" ]
def typed_input(msg, hint=None, in_type=int, default=None): """Ask for user input of a specific type""" res = None while (res is None): try: if (default is not None): assert (isinstance(default, in_type)) input_val = _input(msg + ": [{}] ".format(default)) or default else: input_val = _input(msg + ": ") res = in_type(input_val) except ValueError: if (hint is None): if (in_type == int): print("Please enter an integer number") elif (in_type == float): print("Please enter a number") elif (in_type == IPv4Address): print("Please enter a valid IPv4 address") else: type_str = in_type.__name__ print("Please enter a {}".format(type_str)) else: print(hint) assert (res is not None) assert (isinstance(res, in_type)) return res
[ "def", "typed_input", "(", "msg", ",", "hint", "=", "None", ",", "in_type", "=", "int", ",", "default", "=", "None", ")", ":", "res", "=", "None", "while", "(", "res", "is", "None", ")", ":", "try", ":", "if", "(", "default", "is", "not", "None", ")", ":", "assert", "(", "isinstance", "(", "default", ",", "in_type", ")", ")", "input_val", "=", "_input", "(", "msg", "+", "\": [{}] \"", ".", "format", "(", "default", ")", ")", "or", "default", "else", ":", "input_val", "=", "_input", "(", "msg", "+", "\": \"", ")", "res", "=", "in_type", "(", "input_val", ")", "except", "ValueError", ":", "if", "(", "hint", "is", "None", ")", ":", "if", "(", "in_type", "==", "int", ")", ":", "print", "(", "\"Please enter an integer number\"", ")", "elif", "(", "in_type", "==", "float", ")", ":", "print", "(", "\"Please enter a number\"", ")", "elif", "(", "in_type", "==", "IPv4Address", ")", ":", "print", "(", "\"Please enter a valid IPv4 address\"", ")", "else", ":", "type_str", "=", "in_type", ".", "__name__", "print", "(", "\"Please enter a {}\"", ".", "format", "(", "type_str", ")", ")", "else", ":", "print", "(", "hint", ")", "assert", "(", "res", "is", "not", "None", ")", "assert", "(", "isinstance", "(", "res", ",", "in_type", ")", ")", "return", "res" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L26-L52
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
string_input
(msg, default=None)
return res
Ask for a non-null string input with an optional default value
Ask for a non-null string input with an optional default value
[ "Ask", "for", "a", "non", "-", "null", "string", "input", "with", "an", "optional", "default", "value" ]
def string_input(msg, default=None): """Ask for a non-null string input with an optional default value""" res = "" while (len(res) == 0): if (default is not None): assert (isinstance(default, str)) res = _input(msg + ": [{}] ".format(default)) or default else: res = _input(msg + ": ") return res
[ "def", "string_input", "(", "msg", ",", "default", "=", "None", ")", ":", "res", "=", "\"\"", "while", "(", "len", "(", "res", ")", "==", "0", ")", ":", "if", "(", "default", "is", "not", "None", ")", ":", "assert", "(", "isinstance", "(", "default", ",", "str", ")", ")", "res", "=", "_input", "(", "msg", "+", "\": [{}] \"", ".", "format", "(", "default", ")", ")", "or", "default", "else", ":", "res", "=", "_input", "(", "msg", "+", "\": \"", ")", "return", "res" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L55-L64
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
ask_yes_or_no
(msg, default="y", help_msg=None)
return (response == "y")
Yes or no question Args: msg : the message or question to ask the user default : default response help_msg : Optional help message Returns: True if answer is yes, False otherwise.
Yes or no question
[ "Yes", "or", "no", "question" ]
def ask_yes_or_no(msg, default="y", help_msg=None): """Yes or no question Args: msg : the message or question to ask the user default : default response help_msg : Optional help message Returns: True if answer is yes, False otherwise. """ response = None if (default == "y"): options = "[Y/n]" else: options = "[N/y]" while response not in {"y", "n"}: if (help_msg is None): question = msg + " " + options + " " raw_resp = _input(question) or default else: print(textwrap.fill(msg)) print() print(textwrap.fill(help_msg)) print() raw_resp = _input("Answer " + options + " ") or default response = raw_resp.lower() if (response not in ["y", "n"]): print("Please enter \"y\" or \"n\"") return (response == "y")
[ "def", "ask_yes_or_no", "(", "msg", ",", "default", "=", "\"y\"", ",", "help_msg", "=", "None", ")", ":", "response", "=", "None", "if", "(", "default", "==", "\"y\"", ")", ":", "options", "=", "\"[Y/n]\"", "else", ":", "options", "=", "\"[N/y]\"", "while", "response", "not", "in", "{", "\"y\"", ",", "\"n\"", "}", ":", "if", "(", "help_msg", "is", "None", ")", ":", "question", "=", "msg", "+", "\" \"", "+", "options", "+", "\" \"", "raw_resp", "=", "_input", "(", "question", ")", "or", "default", "else", ":", "print", "(", "textwrap", ".", "fill", "(", "msg", ")", ")", "print", "(", ")", "print", "(", "textwrap", ".", "fill", "(", "help_msg", ")", ")", "print", "(", ")", "raw_resp", "=", "_input", "(", "\"Answer \"", "+", "options", "+", "\" \"", ")", "or", "default", "response", "=", "raw_resp", ".", "lower", "(", ")", "if", "(", "response", "not", "in", "[", "\"y\"", ",", "\"n\"", "]", ")", ":", "print", "(", "\"Please enter \\\"y\\\" or \\\"n\\\"\"", ")", "return", "(", "response", "==", "\"y\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L67-L102
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
ask_multiple_choice
(vec, msg, label, to_str, help_msg=None, none_option=False, none_str="None of the above")
Multiple choice question Args: vec : Vector with elements to choose from msg : Msg to prompt user for choice label : Description/label of what "vec" holdes to_str : Function that prints information about elements help_msg : Optional help message none_option : Whether to display a "none of the above" option none_str : What do display as "none of the above" message Returns: Chosen element
Multiple choice question
[ "Multiple", "choice", "question" ]
def ask_multiple_choice(vec, msg, label, to_str, help_msg=None, none_option=False, none_str="None of the above"): """Multiple choice question Args: vec : Vector with elements to choose from msg : Msg to prompt user for choice label : Description/label of what "vec" holdes to_str : Function that prints information about elements help_msg : Optional help message none_option : Whether to display a "none of the above" option none_str : What do display as "none of the above" message Returns: Chosen element """ if (none_option): assert (len(vec) > 0) else: assert (len(vec) > 1) print(msg) for i_elem, elem in enumerate(vec): elem_str = to_str(elem) print("[%2u] %s" % (i_elem, elem_str)) if (none_option): print("[%2u] %s" % (len(vec), none_str)) if (help_msg is not None): print() print(help_msg) resp = None while (not isinstance(resp, int)): try: resp = int(_input("\n%s number: " % (label))) except ValueError: print("Please choose a number") continue max_resp = len(vec) + 1 if none_option else len(vec) if (resp >= max_resp): print("Please choose number from 0 to %u" % (max_resp - 1)) resp = None continue if (none_option and resp == len(vec)): choice = None print(none_str) else: choice = copy.deepcopy(vec[resp]) # NOTE: deep copy to prevent the caller from changing the original # element. print(to_str(choice)) print() return choice
[ "def", "ask_multiple_choice", "(", "vec", ",", "msg", ",", "label", ",", "to_str", ",", "help_msg", "=", "None", ",", "none_option", "=", "False", ",", "none_str", "=", "\"None of the above\"", ")", ":", "if", "(", "none_option", ")", ":", "assert", "(", "len", "(", "vec", ")", ">", "0", ")", "else", ":", "assert", "(", "len", "(", "vec", ")", ">", "1", ")", "print", "(", "msg", ")", "for", "i_elem", ",", "elem", "in", "enumerate", "(", "vec", ")", ":", "elem_str", "=", "to_str", "(", "elem", ")", "print", "(", "\"[%2u] %s\"", "%", "(", "i_elem", ",", "elem_str", ")", ")", "if", "(", "none_option", ")", ":", "print", "(", "\"[%2u] %s\"", "%", "(", "len", "(", "vec", ")", ",", "none_str", ")", ")", "if", "(", "help_msg", "is", "not", "None", ")", ":", "print", "(", ")", "print", "(", "help_msg", ")", "resp", "=", "None", "while", "(", "not", "isinstance", "(", "resp", ",", "int", ")", ")", ":", "try", ":", "resp", "=", "int", "(", "_input", "(", "\"\\n%s number: \"", "%", "(", "label", ")", ")", ")", "except", "ValueError", ":", "print", "(", "\"Please choose a number\"", ")", "continue", "max_resp", "=", "len", "(", "vec", ")", "+", "1", "if", "none_option", "else", "len", "(", "vec", ")", "if", "(", "resp", ">=", "max_resp", ")", ":", "print", "(", "\"Please choose number from 0 to %u\"", "%", "(", "max_resp", "-", "1", ")", ")", "resp", "=", "None", "continue", "if", "(", "none_option", "and", "resp", "==", "len", "(", "vec", ")", ")", ":", "choice", "=", "None", "print", "(", "none_str", ")", "else", ":", "choice", "=", "copy", ".", "deepcopy", "(", "vec", "[", "resp", "]", ")", "# NOTE: deep copy to prevent the caller from changing the original", "# element.", "print", "(", "to_str", "(", "choice", ")", ")", "print", "(", ")", "return", "choice" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L105-L169
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
print_header
(header, target_len=80)
Print section header
Print section header
[ "Print", "section", "header" ]
def print_header(header, target_len=80): """Print section header""" prefix = "" suffix = "" header_len = len(header) + 2 remaining = target_len - header_len prefix_len = int(remaining / 2) suffix_len = int(remaining / 2) if (remaining % 1 == 1): prefix_len += 1 for i in range(0, prefix_len): prefix += "-" for i in range(0, suffix_len): suffix += "-" print("\n" + prefix + " " + header + " " + suffix)
[ "def", "print_header", "(", "header", ",", "target_len", "=", "80", ")", ":", "prefix", "=", "\"\"", "suffix", "=", "\"\"", "header_len", "=", "len", "(", "header", ")", "+", "2", "remaining", "=", "target_len", "-", "header_len", "prefix_len", "=", "int", "(", "remaining", "/", "2", ")", "suffix_len", "=", "int", "(", "remaining", "/", "2", ")", "if", "(", "remaining", "%", "1", "==", "1", ")", ":", "prefix_len", "+=", "1", "for", "i", "in", "range", "(", "0", ",", "prefix_len", ")", ":", "prefix", "+=", "\"-\"", "for", "i", "in", "range", "(", "0", ",", "suffix_len", ")", ":", "suffix", "+=", "\"-\"", "print", "(", "\"\\n\"", "+", "prefix", "+", "\" \"", "+", "header", "+", "\" \"", "+", "suffix", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L172-L191
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
print_sub_header
(header, target_len=60)
Print sub-section header
Print sub-section header
[ "Print", "sub", "-", "section", "header" ]
def print_sub_header(header, target_len=60): """Print sub-section header""" print_header(header, target_len=target_len)
[ "def", "print_sub_header", "(", "header", ",", "target_len", "=", "60", ")", ":", "print_header", "(", "header", ",", "target_len", "=", "target_len", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L194-L196
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
get_home_dir
()
return os.path.expanduser("~" + user)
Get the user's home directory even if running with sudo
Get the user's home directory even if running with sudo
[ "Get", "the", "user", "s", "home", "directory", "even", "if", "running", "with", "sudo" ]
def get_home_dir(): """Get the user's home directory even if running with sudo""" sudo_user = os.environ.get('SUDO_USER') user = sudo_user if sudo_user is not None else "" return os.path.expanduser("~" + user)
[ "def", "get_home_dir", "(", ")", ":", "sudo_user", "=", "os", ".", "environ", ".", "get", "(", "'SUDO_USER'", ")", "user", "=", "sudo_user", "if", "sudo_user", "is", "not", "None", "else", "\"\"", "return", "os", ".", "path", ".", "expanduser", "(", "\"~\"", "+", "user", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L206-L210
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
_print_urlretrieve_progress
(block_num, block_size, total_size)
Print progress on urlretrieve's reporthook
Print progress on urlretrieve's reporthook
[ "Print", "progress", "on", "urlretrieve", "s", "reporthook" ]
def _print_urlretrieve_progress(block_num, block_size, total_size): """Print progress on urlretrieve's reporthook""" downloaded = block_num * block_size progress = 100 * downloaded / total_size if (total_size > 0): print("Download progress: {:4.1f}%".format(progress), end='\r') if (progress >= 100): print("")
[ "def", "_print_urlretrieve_progress", "(", "block_num", ",", "block_size", ",", "total_size", ")", ":", "downloaded", "=", "block_num", "*", "block_size", "progress", "=", "100", "*", "downloaded", "/", "total_size", "if", "(", "total_size", ">", "0", ")", ":", "print", "(", "\"Download progress: {:4.1f}%\"", ".", "format", "(", "progress", ")", ",", "end", "=", "'\\r'", ")", "if", "(", "progress", ">=", "100", ")", ":", "print", "(", "\"\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L335-L342
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
download_file
(url, destdir, dry_run, logger=None)
return local_path
Download file from a given URL Args: url : Download URL. destdir : Destination directory. dry_run : Dry-run mode. logger : Optional logger to print messages. Returns: Path to downloaded file if the download is successful. None in dry-run mode or if the download fails.
Download file from a given URL
[ "Download", "file", "from", "a", "given", "URL" ]
def download_file(url, destdir, dry_run, logger=None): """Download file from a given URL Args: url : Download URL. destdir : Destination directory. dry_run : Dry-run mode. logger : Optional logger to print messages. Returns: Path to downloaded file if the download is successful. None in dry-run mode or if the download fails. """ filename = url.split('/')[-1] local_path = os.path.join(destdir, filename) if (dry_run): print("Download: {}".format(url)) print("Save at: {}".format(destdir)) return if (logger is not None): logger.debug("Download {} and save at {}".format(url, destdir)) try: urlretrieve(url, local_path, _print_urlretrieve_progress) except HTTPError as e: logger.error(str(e)) return return local_path
[ "def", "download_file", "(", "url", ",", "destdir", ",", "dry_run", ",", "logger", "=", "None", ")", ":", "filename", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "local_path", "=", "os", ".", "path", ".", "join", "(", "destdir", ",", "filename", ")", "if", "(", "dry_run", ")", ":", "print", "(", "\"Download: {}\"", ".", "format", "(", "url", ")", ")", "print", "(", "\"Save at: {}\"", ".", "format", "(", "destdir", ")", ")", "return", "if", "(", "logger", "is", "not", "None", ")", ":", "logger", ".", "debug", "(", "\"Download {} and save at {}\"", ".", "format", "(", "url", ",", "destdir", ")", ")", "try", ":", "urlretrieve", "(", "url", ",", "local_path", ",", "_print_urlretrieve_progress", ")", "except", "HTTPError", "as", "e", ":", "logger", ".", "error", "(", "str", "(", "e", ")", ")", "return", "return", "local_path" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L345-L376
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
ProcessRunner._get_cmd_str
(self, orig_cmd)
return "> " + " ".join(quoted_cmd)
Generate string for command If any argument is supposed to be quoted (i.e., has spaces), add the quotes.
Generate string for command
[ "Generate", "string", "for", "command" ]
def _get_cmd_str(self, orig_cmd): """Generate string for command If any argument is supposed to be quoted (i.e., has spaces), add the quotes. """ quoted_cmd = orig_cmd.copy() for i, elem in enumerate(quoted_cmd): if (" " in elem): quoted_cmd[i] = "\'{}\'".format(elem) return "> " + " ".join(quoted_cmd)
[ "def", "_get_cmd_str", "(", "self", ",", "orig_cmd", ")", ":", "quoted_cmd", "=", "orig_cmd", ".", "copy", "(", ")", "for", "i", ",", "elem", "in", "enumerate", "(", "quoted_cmd", ")", ":", "if", "(", "\" \"", "in", "elem", ")", ":", "quoted_cmd", "[", "i", "]", "=", "\"\\'{}\\'\"", ".", "format", "(", "elem", ")", "return", "\"> \"", "+", "\" \"", ".", "join", "(", "quoted_cmd", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L220-L231
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
ProcessRunner.create_file
(self, content, path, **kwargs)
Create file with given content on a specified path If the target path requires root privileges, this function can be executed with option root=True.
Create file with given content on a specified path
[ "Create", "file", "with", "given", "content", "on", "a", "specified", "path" ]
def create_file(self, content, path, **kwargs): """Create file with given content on a specified path If the target path requires root privileges, this function can be executed with option root=True. """ if (self.dry): # In dry-run mode, run an equivalent echo command. cmd = ["echo", "-e", repr(content), ">", path] else: tmp_file = tempfile.NamedTemporaryFile(mode="w", delete=False) with tmp_file as fd: fd.write(content) cmd = ["mv", tmp_file.name, path] self.run(cmd, **kwargs) if (not self.dry): self.logger.info("Created file {}".format(path))
[ "def", "create_file", "(", "self", ",", "content", ",", "path", ",", "*", "*", "kwargs", ")", ":", "if", "(", "self", ".", "dry", ")", ":", "# In dry-run mode, run an equivalent echo command.", "cmd", "=", "[", "\"echo\"", ",", "\"-e\"", ",", "repr", "(", "content", ")", ",", "\">\"", ",", "path", "]", "else", ":", "tmp_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "\"w\"", ",", "delete", "=", "False", ")", "with", "tmp_file", "as", "fd", ":", "fd", ".", "write", "(", "content", ")", "cmd", "=", "[", "\"mv\"", ",", "tmp_file", ".", "name", ",", "path", "]", "self", ".", "run", "(", "cmd", ",", "*", "*", "kwargs", ")", "if", "(", "not", "self", ".", "dry", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Created file {}\"", ".", "format", "(", "path", ")", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L284-L301
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
Pipe.__init__
(self)
Create unnamed pipe
Create unnamed pipe
[ "Create", "unnamed", "pipe" ]
def __init__(self): """Create unnamed pipe""" r_fd, w_fd = os.pipe() self.r_fd = r_fd # read file descriptor self.r_fo = os.fdopen(r_fd, "r") # read file object self.w_fd = w_fd # write file descriptor self.w_fo = os.fdopen(w_fd, "w")
[ "def", "__init__", "(", "self", ")", ":", "r_fd", ",", "w_fd", "=", "os", ".", "pipe", "(", ")", "self", ".", "r_fd", "=", "r_fd", "# read file descriptor", "self", ".", "r_fo", "=", "os", ".", "fdopen", "(", "r_fd", ",", "\"r\"", ")", "# read file object", "self", ".", "w_fd", "=", "w_fd", "# write file descriptor", "self", ".", "w_fo", "=", "os", ".", "fdopen", "(", "w_fd", ",", "\"w\"", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L306-L314
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
Pipe.__del__
(self)
Close pipe
Close pipe
[ "Close", "pipe" ]
def __del__(self): """Close pipe""" self.r_fo.close() self.w_fo.close()
[ "def", "__del__", "(", "self", ")", ":", "self", ".", "r_fo", ".", "close", "(", ")", "self", ".", "w_fo", ".", "close", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L316-L319
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
Pipe.readline
(self)
return self.r_fo.readline()
Read line from pipe file
Read line from pipe file
[ "Read", "line", "from", "pipe", "file" ]
def readline(self): """Read line from pipe file""" return self.r_fo.readline()
[ "def", "readline", "(", "self", ")", ":", "return", "self", ".", "r_fo", ".", "readline", "(", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L321-L323
Blockstream/satellite
7948ba8f568718008529951c81625ebe5a759bdf
blocksatcli/util.py
python
Pipe.write
(self, data)
Write data to pipe file Args: data : The data to write into the pipe file
Write data to pipe file
[ "Write", "data", "to", "pipe", "file" ]
def write(self, data): """Write data to pipe file Args: data : The data to write into the pipe file """ self.w_fo.write(data)
[ "def", "write", "(", "self", ",", "data", ")", ":", "self", ".", "w_fo", ".", "write", "(", "data", ")" ]
https://github.com/Blockstream/satellite/blob/7948ba8f568718008529951c81625ebe5a759bdf/blocksatcli/util.py#L325-L332